What is the difference between array_walk and array_map?

Asked

Viewed 1,274 times

4

In PHP, we have two functions that traverse the array and apply a function determined for 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);

Exit:

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);

Exit:

array (size=3)
  0 => int 2
  1 => int 4
  2 => int 6

Besides the fact that one uses a reference passage and the other does not, it seems that in the end the two do the same thing.

So:

  • Is there any difference between array_map and array_walk - disregarding the differences already cited?

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

1 answer

4


In addition to one using reference and another returning 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 the array_walk we can provide for the function callback extra arguments. The array_walk allows working with array keys as well:

<?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 "
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.