PHP數組函數array

來源:互聯網
上載者: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

<?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 數組函數總結


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.