PHP array_walk Function: Complete Guide

The array_walk function is used to apply a user-defined function to each element in an array. Its syntax is as follows:

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

Parameter description:

  1. $array: the array to be processed
  2. $callback: custom function to operate on each element in the array
  3. $userdata (optional): Additional parameters passed to the callback function.

Can you please give me some guidance on this issue?

Could you provide me with some advice on this matter?

// 定义自定义函数
function myFunction(&$value, $key, $userdata) {
    $value = $value * $userdata;
}

// 定义数组
$array = [1, 2, 3, 4, 5];

// 使用array_walk函数应用自定义函数
array_walk($array, 'myFunction', 2);

// 打印处理后的数组
print_r($array);

In the example above, the custom function myFunction multiplies each element in the array by the $userdata parameter that is passed in. By calling the custom function using the array_walk function, the array is processed and the processed array is then printed.

bannerAds