陣列是儲存格的概念,從第 0 個儲存格開始,在儲存格內放入值。
<?php
$colors = array("red", "green", "blue");
echo $colors[0]."<br>";
echo $colors[1]."<br>";
echo $colors[2]."<br>";
?>
<?php
$scores = array("math" => 85, "english" => 90, "science" => 76);
echo $scores["math"]."<br>";
echo $scores["english"]."<br>";
echo $scores["science"]."<br>";
?>
這兩者差別在索引的形式,內部的值皆可放數字及字串。
我們可以用 var_dump()
和 print_r()
來看陣列的所有內容
<?php
$colors = array("red", "green", "blue");
var_dump($colors); //較詳細
echo "<br>";
print_r($colors); //較簡潔
echo "<br>";
?>
<?php
$scores = array("math" => 85, "english" => 90, "science" => 76);
var_dump($scores); //較詳細
echo "<br>";
print_r($scores); //較簡潔
echo "<br>";
?>
我們也可以直接指定索引及變數,將資料指派進去
<?php
$colors = array("red", "green", "blue");
$colors[3] = "yellow";
$colors[5] = 123;
print_r($colors);
echo "<br>";
?>
<?php
$scores = array("math" => 85, "english" => 90, "science" => 76);
$scores["chinese"] = 666;
$scores[4] = "100分";
print_r($scores);
echo "<br>";
?>
若不指定索引,預設為數字編號
<?php
$cityArray[] = "Taipei";
$cityArray[] = "Taichung";
$cityArray[] = "Tainan";
print_r($cityArray);
?>
<?php
$scores["math"] = 87;
$scores["english"] = 92;
$scores["science"] = 79;
$subject = "english";
echo "My ".$subject." test is ".$scores[$subject]." points.<br>";
$subject = "math";
echo "My ".$subject." test is ".$scores[$subject]." points.<br>";
?>
<?php
$numbers = array(array(1,2,3), array(4,5,6), array(7,8,9));
print_r($numbers);
echo "<br>".$numbers[1][0];
?>
有點類似 HTML 提過的表格的概念
<?php
$data = array(
"Elsa"=>array(
"Math"=>78,
"Eng"=>98
),
"Anna"=>array(
"Math"=>80,
"Eng"=>56
)
);
print_r($data);
echo "<br>".$data["Anna"]["Math"];
?>
<?php
$student["Elsa"]= array("Math"=>78,"Eng"=>98);
$student["Anna"]= array("Math"=>80,"Eng"=>56);
print_r($student);
echo "<br>".$student["Anna"]["Math"];
?>
請問這樣也是一種陣列使用方式嗎?
<?php
$ARRAY2['NO1']="test1";
echo $ARRAY2['NO1']."<br />";;
foreach($ARRAY2 as $keys=>$values){
echo $keys."=>".$values."<br />";
}
?>
你是說 foreach ($陣列 as $索引 => $值)
嗎?
這是可以一次取陣列所有值的一種方式沒錯
不是,是指
$ARRAY2['NO1']="test1";
在此之前我以為都要事先array("test1","test2")宣告才可以使用
像
$colors = array("red", "green", "blue");
原來還可以直接使用
我發文之後才發現您這篇文章最後有這個範例
$student["Elsa"]= array("Math"=>78,"Eng"=>98);
喔喔~ 原來是說這個
恩 $ARRAY2['NO1']="test1";
這種就是可以自己指定索引名稱
也可以不指定[]內容,預設就是數字索引
當然也可以用array()來宣告