简体   繁体   中英

PHP array_walk doesn't change the array's values

I have this simple code:

$postCopy = $_POST['adminpanel'];
array_walk($postCopy, function($v, $k) {
    return '';
});

I did var_dump for postCopy before and after array_walk execution. In both var_dump executions, I get the same result:

array(2) { ["usefulinfo_countryfilescount"]=> string(1) "3" ["strageticoverviews_filesinpagecount"]=> string(1) "3" }

So it means that array_walk didn't execute correctly, because if it would- I'd get an array with '' values...

You just forgot to pass argument by reference :

$postCopy = $_POST['adminpanel'];
array_walk($postCopy, function(&$v, $k) {
    $v = '';
});

From the manual :

Note :

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference . Then, any changes made to those elements will be made in the original array itself.

So you need to change your call to:

array_walk($postCopy, function(&$v, $k) {
  $v = "";
});

Note the & in the argument list. The return value of callback is not actually used.

Also, consider using array_map , if you are modifying all elements of an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM