How is the array_walk function used in PHP?

The array_walk function in PHP is used to apply a user-defined function to all elements of an array. Here is how it is used:

Iterate through the elements of the array using a callback function and optional userdata parameter.

$array is the array to be processed, $callback is a user-defined function used to perform a task on each element of the array, and $userdata is an optional parameter for passing additional user-defined data to the callback function.

The definition of a callback function is as follows:

callback function which accepts three parameters: value, key, and userdata

In the callback function, $value represents the value of the array element, $key represents the key of the array, and $userdata represents the $userdata parameter passed to the array_walk function.

Using the array_walk function, the same handling logic can be applied to each element of the array, allowing for modification of the original array or returning a new array.

Here is an example of using the array_walk function:

The output result is:

Array containing different types of fruits like apple, banana, and cherry.

In the example above, the function “myfunction” concatenates each array element with $userdata and assigns the result back to the original array element, achieving modification of the original array.

bannerAds