php如何建立數組填充數組

來源:互聯網
上載者:User
在PHP以及其他程式語言程式設計中,經常會用到數組的建立,在前端開發中,js的數組建立可以由[]和new Array()直接建立和賦值。然而PHP建立數組的方法有哪些呢?在查閱資料並且網上收集整理總結了下:







1. 使用array建立數組,是最常見和便捷的一個方式 :


$arr = array('a','b','c');$arr[] = 'a' ; $arr[] = 'b' ; $arr[] = 'c';$arr = array('name' => '關羽' , 'age' => 23 , 'sex' => '男');

2. 有時候需要建立一個長度為len的一個隨機數組,所以就可以用range():

定義:array range(first,second,step) //first:元素最小值 second:元素最大值 step:元素步長(要增加的量)


$number = range(0,5); print_r ($number); //列印:Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 [4] => 4 [5] => 5 ) $number = range(0,50,10); print_r ($number); //列印:Array ( [0] => 0 [1] => 10 [2] => 20 [3] => 30 [4] => 40 [5] => 50 ) $letter = range("a","d"); print_r ($letter); //列印:Array ( [0] => a [1] => b [2] => c [3] => d )

3.當然,在某些特定需求下,需要把某些變數存入數組,這些變數的變數名轉換成鍵名,變數值轉換成索引值(前提:該變數存在):


$firstname = "Peter"; $lastname = "Griffin"; $age = "38"; $result = compact("firstname", "lastname", "age"); print_r($result); //列印: Array ( [firstname] => Peter [lastname] => Griffin [age] => 38 ) $firstname = "Peter"; $lastname = "Griffin"; $age = "38"; $name = array("firstname", "lastname"); $result = compact($name, "location", "age"); print_r($result); //列印:Array ( [firstname] => Peter [lastname] => Griffin [age] => 38 ) //由於$location變數不存在,所以存入不了數組

4. 將兩個數組合并為一個新的數組,第一個數組的值是新數組的鍵名,第二個數組裡面的值是新數組的索引值:

定義:array_combine()函數可以將兩個數組合并成一個新數組,其中的一個數組是鍵名,另一個數組的值為索引值。


$a1=array("a","b","c","d"); $a2=array("Cat","Dog","Horse","Cow"); print_r(array_combine($a1,$a2)); //列印:Array ( [a] => Cat [b] => Dog [c] => Horse [d] => Cow )

5. 建立索引值一樣具有固定長度的數組:

定義:array_fill(start,number,value) //start:起始索引 number:值的個數 value:數組值

$a=array_fill(2,3,"Dog"); print_r($a); //列印:Array ( [2] => Dog [3] => Dog [4] => Dog )

聯繫我們

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