陣列是一個可以儲存很多值變數,與變數相同,提供儲存記憶體空間,可以建立一維、二維陣列。在PHP中不需要事先宣告陣列大小,讓記憶體有許多彈性。
<?php
$classmate[0] = "Alicia";
$classmate[1] = "Balo";
$classmate[2] = "Cindy";
$classmate[3] = "David";
echo $classmate[0]."</br>";
for($var = 0; $var < count($classmate);$var++){
echo $classmate[$var]."</br>";
}
?>
輸出:
Alicia
Alicia
Balo
Cindy
David
印出陣列所有內容,使用for迴圈,計算陣列長度:count()、sizeof()。
當索引值為數字時可省略:
<?php
$classmate = array("Alicia","Balo","Cindy","David");
echo $classmate[0]."</br>";
for($var = 0; $var < sizeof($classmate);$var++){
echo $classmate[$var]."</br>";
}
?>
輸出:
Alicia
Alicia
Balo
Cindy
David
其中的索引值可以自己命名。
<?php
$myarr = array("Girlfriend"=>"Alicia","Dad"=>"Balo","Mom"=>"Cindy");
echo "my girlfriend is ".$myarr['Girlfriend'];
?>
輸出:
my girlfriend is Alicia