How to Use the PHP array_walk() Function

09/06/2021

Contents

In this article, you will learn how to use the PHP array_walk() function.

PHP array_walk() Function

The array_walk() function is a built-in PHP function that allows you to apply a user-defined function to each element of an array.

Syntax:
array_walk(array &$array, callable $callback [, mixed $userdata = NULL]);
Parameters:
  • $array: The input array that you want to apply the function to.
  • $callback: The function that you want to apply to each element of the array. This function must accept two arguments: the value of the current element, and the key of the current element.
  • $userdata (optional): An additional argument that you can pass to the callback function.
Example:
<?php
  $fruits = array("apple", "banana", "cherry");

  function print_value($value, $key) {
    echo "$key: $value\n";
  }

  array_walk($fruits, 'print_value');

  // Output:
  // 0: apple
  // 1: banana
  // 2: cherry
?>

In this example, the array_walk() function applies the print_value function to each element of the $fruits array.

Here are some additional details and tips regarding the array_walk() function:

  • The array_walk() function modifies the input array directly, so you don’t need to assign the result of the function to a new array.
  • The callback function can modify the values of the array elements, for example:

    <?php
      $numbers = array(1, 2, 3, 4, 5);
    
      function add_one(&$value, $key) {
        $value++;
      }
    
      array_walk($numbers, 'add_one');
    
      print_r($numbers);
    
      // Output:
      // Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 5 [4] => 6 )
    ?>
  • The array_walk() function returns TRUE on success and FALSE on failure. In most cases, it is not necessary to check the return value of array_walk(), since the function modifies the input array directly.
  • If the callback function returns FALSE, array_walk() will terminate immediately and not process any further elements.
  • If you need to pass additional data to the callback function, you can use the use keyword to bind values to variables within the function’s scope:

    <?php
      $fruits = array("apple", "banana", "cherry");
      $prefix = "fruit: ";
    
      function print_value($value, $key, $prefix) {
        echo "$key: $prefix$value\n";
      }
    
      array_walk($fruits, function($value, $key) use ($prefix) {
        print_value($value, $key, $prefix);
      });
    
      // Output:
      // 0: fruit: apple
      // 1: fruit: banana
      // 2: fruit: cherry
    ?>