In PHP, we have two functions that run through the array and apply a given function to each element: array_walk and array_map.
Example:
$meu_array = array(1, 2, 3);
$callback = function ($value)
{
return $value * 2;
};
$novo_array = array_map($callback, $meu_array);
var_dump($novo_array);
Output:
array (size=3)
0 => int 2
1 => int 4
2 => int 6
Example 2:
$novo_array = $meu_array;
$callback = function (&$value)
{
$value *= 2;
};
array_walk($novo_array, $callback);
var_dump($novo_array);
Output:
array (size=3)
0 => int 2
1 => int 4
2 => int 6
In addition to the fact that one uses reference passing and another does not, it seems that in the end both do the same thing.
Thus:
-
Is there any difference between
array_map
andarray_walk
- disregarding the differences already mentioned? -
When is it recommended to use one or the other?