PHP array_walk() Function

PHP Array Reference : Run each array element in a user-defined function

Definition and Usage

The array_walk() function runs each array element in a user-defined function. The array's keys and values are parameters in the function.

Note: You can change an array element's value in the user-defined function by specifying the first parameter as a reference: &$value (See Example 2).
Tip: To work with deeper arrays (an array inside an array), use the array_walk_recursive() function.

Syntax

array_walk(array, myfunction, parameter...)

Parameter Values

Parameter Description
array Required. Specifying an array
myfunction Required. The name of the user-defined function
parameter,... Optional. Specifies a parameter to the user-defined function. You can assign one parameter to the function, or as many as you like

Technical Details

Return Value: Returns TRUE on success or FALSE on failure
PHP Version: 4+

More Examples

Example 1

With a parameter:

<?php
function myfunction($value,$key,$p)
{
echo "$key $p $value<br>";
}
$a=array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a,"myfunction","has the value");
?>

Example 2

Change an array element's value. (Notice the &$value)

<?php
function myfunction(&$value,$key)
{
$value="yellow";
}
$a=array("a"=>"red","b"=>"green","c"=>"blue");
array_walk($a,"myfunction");
print_r($a);
?>

❮ PHP Array Reference