Current Location: Home> Function Categories> array_walk

array_walk

Use user-defined functions to make callbacks to each element in the array
Name:array_walk
Category:Array
Programming Language:php
One-line Description:Applies user functions to each member in the array.

Definition and usage

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

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

Tip: To operate deeper arrays (one array contains another array), use array_walk_recursive() function.

Example

Example 1

Apply user-defined functions 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" ) ;
?>

Try it yourself

Example 2

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

Try it yourself

Example 3

Change the value of an array element (note &$value):

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

Try it yourself

grammar

 array_walk ( array , myfunction , userdata ... )
parameter describe
array Required. Specify array.
myfunction Required. The name of the user-defined function.
userdata ,... Optional. Specifies the parameters of the user-defined function. You can pass as many parameters as you like to this function.

illustrate

array_walk() function applies a callback function to each element in the array. Return TRUE if successful, otherwise return FALSE.

Typically myfunction accepts two parameters. The value of the array parameter is the first and the key name is the second. If the optional parameter userdata is provided, it will be passed to the callback function as the third parameter.

If the myfunction function requires more parameters than given, an E_WARNING-level error will be generated every time array_walk() calls myfunction . These warnings can be suppressed by adding PHP's error operator @ before array_walk() call, or by using error_reporting() .

Note: If the callback function needs to act directly on the value in the array, you can specify the first parameter of the callback function as a reference: &$value. (See Example 3)

Note: Passing the key name and userdata into myfunction is a new addition to PHP 4.0.

Similar Functions
Popular Articles