Latest web development tutorials

PHP array_walk () function

PHP Array Reference Complete PHP Array Reference

Examples

Each element in the array application 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");
?>

Running instance »

Definition and Usage

array_walk () function for each element in the array apply user-defined functions. In the function, the array of key names and values ​​are parameters.

Note: You can use the user-defined function in the first parameter specified as a reference: & $ value, to change the value of array elements (see Example 2).

Tip: To operate a deeper array (an array that contains another array), use array_walk_recursive () function.


grammar

array_walk( array,myfunction,parameter... )

参数 描述
array 必需。规定数组。
myfunction 必需。用户自定义函数的名称。
parameter,... 可选。规定用户自定义函数的参数,您可以为函数设置一个或多个参数。

technical details

return value: If successful it returns TRUE, otherwise returns FALSE.
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");
?>

Running instance »

Example 2

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

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

Running instance »


PHP Array Reference Complete PHP Array Reference