PHP array_walk()Functions

PHP Array ReferenceComplete PHP Array Reference Manual

Example

Apply a user-defined function to each element in the array:

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

Run Example »

Definition and Usage

The array_walk() function applies a user-defined function to each element in the array. In the function, the array's key name and key value are parameters.

Note:You can change the value of array elements by specifying the first parameter of the user-defined function as a reference: &$value (see Example 2).

Tip:To operate on deeper arrays (an array containing another array), use thearray_walk_recursive()function.


Syntax

array_walk(array,myfunction,parameter...)

Parameter Description
array Required. Specifies the array.
myfunction Required. The name of the user-defined function.
parameter,... Optional. Specifies the parameters of the user-defined function. You can set one or more parameters for the function.

Technical Details

Return value: Returns TRUE on success, or FALSE otherwise.
PHP Version: 4+


More Examples

Example 1

With one 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");
?>

Run Example »

Example 2

Change the value of array elements (note the &$value):

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

Run Example »


PHP Array ReferenceComplete PHP Array Reference Manual Other Extensions