Home » Php » PHP array_walk doesn't change the array's values

PHP array_walk doesn't change the array's values

Posted by: admin February 25, 2020 Leave a comment


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…

How to&Answers:

From the manual:


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.


You just forgot to pass argument by reference :

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