在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 )
相關推薦:
以上是php如何建立數組填充數組的詳細內容。更多資訊請關注PHP中文網其他相關文章!