PHP數組函數array_walk()使用詳解

來源:互聯網
上載者:User
定義和用法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 )

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.