What is the purpose of array_walk in PHP?
array_walk is a function in PHP that applies a user-defined callback function to each element in an array.
Its purpose is to iterate through each element of an array, passing each element as a parameter to a callback function for processing. The callback function can modify the elements in the original array or return a new element value, allowing for customized operations on the array.
The syntax of array_walk is as follows:
array_walk(array &$array, callable $callback [, mixed $userdata = NULL]): bool
Where $array represents the array to be traversed, $callback represents the callback function used to process each array element, and $userdata is optional user-defined data that can be used in the callback function.
Original: 他喜欢看电影,但是他更喜欢阅读书籍。
Paraphrase: He enjoys watching movies, but he prefers reading books even more.
function multiply(&$value, $key, $factor) {
$value *= $factor;
}
$numbers = [1, 2, 3, 4, 5];
array_walk($numbers, 'multiply', 2);
print_r($numbers);
In the above example, a callback function called multiply is defined to multiply array elements by a specified factor. The array_walk function is then used to apply the multiply function to each element in the $numbers array, resulting in the final output of [2, 4, 6, 8, 10].
Therefore, the purpose of the array_walk function is to apply a custom operation to each element in an array in order to achieve batch processing of the array.