定義
array_walk - 對陣列的每個元素應用自定義函式
描述
array_walk ( array &$array , callable $callback [, mixed $userdata = https://www.cnblogs.com/jiaoran/p/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 一遍.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/63424.html
標籤:PHP
