PHP Function Reference

PHP array_walk() Function



The PHP array_walk() function applies the user-defined function to each element of the array. This function is not affected by the internal array pointer of array and walk through the entire array regardless of pointer position.

Syntax

array_walk(array, myfunction, arg)

Parameters

array Required. Specify the input array.
myfunction Required. Specify user-defined function. Typically it takes two parameters. First parameter as array's value and second parameter as array's key. A third parameter can be passed using arg parameter of the array_walk() function. Please note that only the values of the array may potentially be changed.
arg Optional. If provided, it is passed as the third parameter to the myfunction.

Note: If myfunction needs to be working with the actual values of the array, specify the first parameter of myfunction as a reference. Then, any changes made to those elements will be made in the original array itself.

Return Value

Returns true.

Exceptions

As of PHP 7.1.0, an ArgumentCountError is thrown if myfunction requires more than 2 parameters. Previously, if the myfunction required more than 2 parameters, an error of level E_WARNING is thrown each time array_walk() calls myfunction.

Example:

In the example below, the array_walk() function is used to print the content of the array.

<?php
function MyFunc1($value, $key) {
  echo "$key = $value \n";
}

function MyFunc2($value, $key, $p) {
  echo "$key $p $value. \n";
}

$Arr = array("Red"=>10, 
             "Green"=>20,
             "Blue"=>30);

array_walk($Arr, 'MyFunc1');
echo "\n";
array_walk($Arr, 'MyFunc2', 'has the value');
?>

The output of the above code will be:

Red = 10 
Green = 20 
Blue = 30 

Red has the value 10. 
Green has the value 20. 
Blue has the value 30. 

Example:

Consider one more example where value is passed as reference. Any changes made to these values will change the original array itself.

<?php
function MyFunc(&$value, $key) {
  $value = $value**3;
}

$Arr = array(1, 2, 3, 4, 5);

echo "Before applying array_walk() function:\n";
print_r($Arr);

//applying array_walk() function
array_walk($Arr, 'MyFunc');

echo "\nAfter applying array_walk() function:\n";
print_r($Arr);
?>

The output of the above code will be:

Before applying array_walk() function:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)

After applying array_walk() function:
Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)

❮ PHP Array Reference