What are array_map(), array_reduce() and array_walk() function in PHP ?
array_map()
, array_reduce()
, and array_walk()
are built-in PHP functions that are used to manipulate arrays.
array_map()
: This function applies a callback function to each element of an array and returns a new array with the modified elements. The syntax forarray_map()
is as follows:
array_map(callable $callback, array $array1 [, array $... ])
Example:
function square($n) {
return $n * $n;
}
$numbers = [1, 2, 3, 4, 5];
$squares = array_map("square", $numbers);
print_r($squares); // Output: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25 )
array_reduce()
: This function reduces an array to a single value by applying a callback function to each element of the array. The syntax forarray_reduce()
is as follows:
array_reduce(array $array, callable $callback [, mixed $initial = NULL ])
Example:
function sum($carry, $item) {
$carry += $item;
return $carry;
}
$numbers = [1, 2, 3, 4, 5];
$total = array_reduce($numbers, "sum");
echo $total; // Output: 15
array_walk()
: This function applies a callback function to each element of an array. The syntax forarray_walk()
is as follows:
array_walk(array &$array, callable $callback [, mixed $userdata = NULL ])
Example:
function add_hello(&$value, $key) {
$value = "Hello " . $value;
}
$names = ["Alice", "Bob", "Charlie"];
array_walk($names, "add_hello");
print_r($names); // Output: Array ( [0] => Hello Alice [1] => Hello Bob [2] => Hello Charlie )
Note: In array_walk()
, the first parameter is passed by reference, so any changes made to the array inside the callback function will affect the original array.