定義和用法array_walk() 函數對數組中的每個元素應用回呼函數。
如果成功則返回 TRUE,否則返回 FALSE。典型情況下 function 接受兩個參數。array 參數的值作為第一個,鍵名作為第二個。
如果提供了選擇性參數 userdata ,將被作為第三個參數傳遞給回呼函數。如果 function 函數需要的參數比給出的多,則每次 array_walk() 調用 function 時都會產生一個 E_WARNING 級的錯誤。
這些警告可以通過在 array_walk() 調用前加上 PHP 的錯誤操作符 @ 來抑制,或者用 error_reporting()。文法array_walk(array,function,userdata...)參數描述array必需。規定數組。function必需。使用者自訂函數的名稱。userdata可選。使用者輸入的值,可作為回呼函數的參數。提示和注釋提示:您可以為函數設定一個或多個參數。注釋:如果回呼函數需要直接作用於數組中的值,可以將回呼函數的第一個參數指定為引用:&$value。(參見例子 3)注釋:將鍵名和 userdata 傳遞到 function 中是 PHP 4.0 新增加的。
例子 1
function myfunction($value, $key) {
echo "The key $key has the value $value
";
}
$a = array("a" => "Cat", "b" => "Dog", "c" => "Horse");
array_walk($a, "myfunction");
輸出:
The key a has the value Cat
The key b has the value Dog
The key c has the value Horse
例子 2
帶有一個參數:
function myfunction($value, $key, $p) {
echo "$key $p $value
";
}
$a = array("a" => "Cat", "b" => "Dog", "c" => "Horse");
array_walk($a, "myfunction", "has the value");
?>
輸出:
a has the value Cat
b has the value Dog
c has the value Horse
例子 3
改變數組元素的值(請注意 &$value):(這種情況用的比較多!)
function myfunction(&$value, $key) {
$value = "Bird";
}
$a = array("a" => "Cat", "b" => "Dog", "c" => "Horse");
array_walk($a, "myfunction");
print_r($a);
輸出:
Array ( [a] => Bird [b] => Bird [c] => Bird )