count 用來計算集合的總數,所以可以用來計算陣列的長度。
在拿取存放在陣列的資料時,經常會使用迴圈來取值,而 count 這個屬性讓陣列的取值更加簡潔明瞭。
把 count($array)
設定為數字範圍,讓變數從 0 開始,小於陣列長度,就能拿取陣列中所有資料了。
<?php
$colors = array("red","blue","green");
for ($i = 0; $i < count($colors); $i++) {
echo $colors[$i]."<br>";
}
?>
foreach 是簡潔快速的 for 迴圈概念,將陣列中的每一個資料取出來。
<?php
$colors = array("red","green","blue");
foreach($colors as $rgb){
echo $rgb."<br>";
}
?>
<?php
$subjects = array(
"chinese" => 87,
"english" => 63,
"math" => 92,
);
foreach($subjects as $subject => $score){
echo $subject." : ".$score."<br>";
}
?>
<?php
$subjects = array(
"chinese" => 87,
"english" => 63,
"math" => 92,
);
var_dump(array_key_exists("math", $subjects));
echo "<br>";
var_dump(array_key_exists("science", $subjects));
?>
<?php
$subjects = array(
"chinese" => 87,
"english" => 63,
"math" => 92,
);
$input = "chinese";
if(array_key_exists($input , $subjects) == true){
echo $input." : ".$subjects[$input]."分<br>";
}else{
echo "查無此科目!";
}
?>
如果是沒有在索引內的
$input = "science";
<?php
$subjects = array(
"chinese" => 87,
"english" => 63,
"math" => 92,
);
var_dump(in_array("87", $subjects));
echo "<br>";
var_dump(in_array("100", $subjects));
?>
<?php
$colors = array("red","green","blue");
$color = "red";
if(in_array($color, $colors) == true){
echo "有 ".$color." 喔!";
} else {
echo "沒有這個顏色喔~";
}
?>
$color = "yellow";
<?php
$subjects = array(
"chinese" => 87,
"english" => 63,
"math" => 92,
);
var_dump(array_search("100", $subjects));
echo "<br>";
var_dump(array_search("87", $subjects));
echo "<br>";
$subject = array_search("87", $subjects);
echo $subject;
?>