PHP array_walk() Function

❮ PHP Array Reference

Example

Run each array element in a user-defined function:

<?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 »

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");
?>
Try it Yourself »

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);
?>
Try it Yourself »

❮ PHP Array Reference
Copyright 1999-2023 by Refsnes Data. All Rights Reserved.