定義
array_walk - 對數組的每個元素應用自定義函數
描述
array_walk ( array &$array , callable $callback [, mixed $userdata = NULL ] ) : bool
回調函數的參數,第一個是元素值,第二個是元素鍵名,第三個是可選的 $userdata
。
如果只想改變數組值,第一個參數可使用引用傳遞,即在參數前加上 &
。
示例
<?php
$fruits = array("a" => "orange", "b" => "banana", "c" => "apple");
function test_alter(&$item1, $key, $prefix)
{
$item1 = "$prefix: $item1";
}
function test_print($item2, $key)
{
echo "$key. $item2<br />\n";
}
echo "Before ...:\n";
array_walk($fruits, 'test_print');
array_walk($fruits, 'test_alter', 'fruit');
echo "... and after:\n";
array_walk($fruits, 'test_print');
?>
將輸出:
Before ...:
a. orange
b. banana
c. apple
... and after:
a. fruit: orange
b. fruit: banana
c. fruit: apple
總結
上面說如果想改變數組的值,必須使用引用傳遞,於是我想能不能不這樣,直接使用返回值,測試了一下,是不行的,因為回調函數的返回值並沒有用到,猜想此函數的目的主要在把數組的每個元素遍歷一下,即 走 walk
一遍.