Difference between array_walk() and array_map() ?

Difference between array_walk() and array_map() ?

Difference between Difference between array_walk() and array_map() ?

laravel Aug 12, 2023

Both array_walk and array_map are PHP functions that apply a callback to each element of an array. However, there are several fundamental differences between the two:

Purpose:

  • array_walk: This function is primarily used for modifying the original array by reference. It's often utilized when you want to change the array's values based on some criteria.
  • array_map: This function returns a new array where each value is the result of applying the callback to the original value. The original array remains unchanged.

Return Value:

  • array_walk: Returns true on success and false on failure. The original array gets modified (unless the callback function doesn't make any modifications).
  • array_map: Returns a new array containing all the elements of the original array after applying the callback function to each one.

Parameters:

  • array_walk: The callback function for array_walk receives each value and key of the array, respectively, as its arguments (and any additional arguments you provide).
  • array_map: The callback function for array_map only receives the array's value as its argument.

Multiple Array Handling:

  • array_walk: Works on one array at a time.
  • array_map: Can operate on multiple arrays at once. If multiple arrays are provided, the callback function should accept that many arguments, and the function is applied to the arrays iteratively. This is useful for combining or comparing multiple arrays' elements.
$array1 = [1, 2, 3];

// Using array_walk:
array_walk($array1, function (&$value, $key) {
    $value = $value * 2;
});
// $array1 is now [2, 4, 6]

$array2 = [1, 2, 3];
$result = array_map(function ($value) {
    return $value * 2;
}, $array2);
// $result is [2, 4, 6], but $array2 is still [1, 2, 3]

In general, you'd use array_walk when you want to modify an array in place and use array_map when you want to generate a new array based on some transformation of the original array.

Tags