在使用 PHP 進行開發的過程中,或早或晚,您會需要創建許多相似的變量。
無需很多相似的變量,你可以把數據作為元素存儲在數組中。
數組中的元素都有自己的 ID,因此可以方便地訪問它們。
有三種數組類型:
數值數組
帶有數字 ID 鍵的數組
例子
$names = array("Peter","Quagmire","Joe");
echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";
以上代碼的輸出:
Quagmire and Joe are Peter's neighbors
關聯數組
數組中的每個 ID 鍵關聯一個值
$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
echo "Peter is " . $ages['Peter'] . " years old.";
以上腳本的輸出:
Peter is 32 years old.
多維數組
包含一個或多個數組的數組
$families = array
(
"Griffin"=>array
(
"Peter",
"Lois",
"Megan"
),
"Quagmire"=>array
(
"Glenn"
),
"Brown"=>array
(
"Cleveland",
"Loretta",
"Junior"
)
);
如果輸出這個數組的話,應該類似這樣:
Array
(
[Griffin] => Array
(
[0] => Peter
[1] => Lois
[2] => Megan
)
[Quagmire] => Array
(
[0] => Glenn
)
[Brown] => Array
(
[0] => Cleveland
[1] => Loretta
[2] => Junior
)
)