PHP web development

What is array_walk in PHP?

In PHP, array_walk() is a built-in function that applies a user-defined function to each element of an array. It takes two parameters: the first is the array, and the second is the function that will be applied to each element of the array.

'array_walk()' is a built-in function in PHP that applies a user-defined function to each element of an array. The function takes two arguments: the value of the current array element and its key (or index). The function is applied to each element in the array, in the order in which they appear.

The syntax for array_walk() is as follows:

array_walk(array, callback, userdata);

  • array is the input array that you want to apply the callback function to
  • callback is the user-defined function that will be applied to each element of the array. The function must take two arguments: the value of the current array element and its key (or index).
  • userdata (optional) is a value that will be passed as an additional parameter to the callback function.
For example, to print the values of an array:

$fruits = array("apple", "banana", "cherry");
function printValue($value, $key) {
echo "Element $key is $value";
}
array_walk($fruits, 'printValue');

array_walk() function returns true if the array is passed to the function, else it returns false

Please note that array_walk() function works on both indexed and associative arrays.

Some of the common use cases of array_walk() function are:
  • Printing the values of an array
  • Modifying the values of an array
  • Calculating the sum or product of all elements of an array
  • Adding the elements of an array to a new array with a specific key
  • Counting the occurrences of specific values in an array
  • Formatting the data of an array for display or storage

Bottom Tags : Web Design Brisbane, Web Development Brisbane, web design company brisbane, Custom Software Development Brisbane