定義和用法
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
<?phpfunction myfunction($value, $key) {echo "The key $key has the value $value<br />";}$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
帶有一個參數:
<?phpfunction myfunction($value, $key, $p) {echo "$key $p $value<br />";}$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):(這種情況用的比較多!)
<?phpfunction 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 )
您可能感興趣的文章
- PHP數組函數array_map()筆記
- PHP 產生連續的數字(字母)數組函數range()分析,PHP抽獎程式函數
- php在數組中尋找某個值是否存在(in_array(),array_search(),array_key_exists())
- php壓入元素到數組頭部(array_unshift的用法)
- PHP去除數組中的空值元素(array_filter)
- 如何刪除PHP數組中的元素(unset,array_splice)?
- 用PHP函數memory_get_usage擷取當前PHP記憶體消耗量以實現程式的效能最佳化
- php 數組函數總結