Current Location: Home> Latest Articles> In-depth Guide to PHP's array_walk() Function with Examples

In-depth Guide to PHP's array_walk() Function with Examples

M66 2025-06-15

What is the array_walk() Function?

The array_walk() function applies a user-defined callback function to each element of an array. It returns TRUE on success and FALSE on failure, allowing developers to process array content flexibly.

Syntax of array_walk() Function

<span class="fun">array_walk(arr, custom_func, parameter)</span>

Parameter Description

  • arr - The array to be traversed, required.
  • custom_func - A user-defined callback function to handle each element of the array, required.
  • parameter - An optional parameter passed to the callback function.

Return Value

The function returns TRUE on success and FALSE if an error occurs.

Example Code

Below is an example demonstrating how to use the array_walk() function:

<?php
function display($val, $key) {
    echo "$key id : Student $val<br>";
}
$arr = array("p" => "Tom", "q" => "Jack", "r" => "Amit");
array_walk($arr, "display");
?>

Example Output

Running the above code will output:

p id : Student Tom
q id : Student Jack
r id : Student Amit

Summary

array_walk() is a very useful function for PHP array operations, suitable for batch processing of array elements with custom logic. Understanding its usage can significantly improve code flexibility and maintainability.