What is the difference between array_walk and array_map?

4

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 and array_walk - disregarding the differences already mentioned?

  • When is it recommended to use one or the other?

asked by anonymous 28.07.2015 / 17:48

1 answer

4

In addition to using a reference and another return a new array, see the signature of both methods:

bool array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] )

array array_map ( callable $callback , array $array1 [, array $... ] )

When using array_walk we can provide for the callback function extra arguments. The array_walk lets you work with the array keys too:

<?php

function mergeValueKey(&$value, $key, $prefix = '')
{
    $value = $prefix . $value . $key;
}

$array = [
    't1' => 'Teste1 ',
    't2' => 'Teste2 ',
    't3' => 'Teste3 ',
];

array_walk($array, 'mergeValueKey');

var_dump($array);

Result with array_walk :

array(3) {
  ["t1"]=>
  string(9) "t1Teste1 "
  ["t2"]=>
  string(9) "t2Teste2 "
  ["t3"]=>
  string(9) "t3Teste3 "
}
    
28.07.2015 / 18:47