<?php
$chicken[0] = 3;
$chicken[1] = 5;
$chicken[2] = 1;
$chicken[3] = 3.4;
$chicken[4] = 2;
$chicken[5] = 50;
?>
例:養雞場有6只雞,,體重分別為3KG、5KG,1KG,3.4KG、2KG和50KG,要求:循環輸出所有雞的體重,並求總體重和平均體重。
<?php
$chicken[0] = 3;
$chicken[1] = 5;
$chicken[2] = 1;
$chicken[3] = 3.4;
$chicken[4] = 2;
$chicken[5] = 50;
$weight = 0;
$avg = 0;
//遍歷數組
for ($i = 0; $i < count($chicken); $i++) {
echo "第" . ($i + 1) . "只雞的體重=" . $chicken[$i] . '<br />';
$weight+=$chicken[$i];
}
$avg = $weight / count($chicken);
echo "共有:" . count($chicken) . "只雞" . '<br />';
echo "總體重是:" . $weight . "<br />";
echo "平均體重是:" . $avg;
?>
基本語法:
$數組名=array(值,……);
$chicker=array(3,5,1,3.4,2,50)
例:養雞場有6只雞,,體重分別為3KG、5KG,1KG,3.4KG、2KG和50KG,要求:循環輸出所有雞的體重,並求總體重和平均體重。用數組的第二種定義方式實現
<?php
$chicken = array(3, 5, 1, 3.4, 2, 50);
$weight = 0;
$avg = 0;
//遍歷數組
for ($i = 0; $i < count($chicken); $i++) {
echo "第" . ($i + 1) . "只雞的體重=" . $chicken[$i] . '<br />';
$weight+=$chicken[$i];
}
$avg = $weight / count($chicken);
echo "共有:" . count($chicken) . "只雞" . '<br />';
echo "總體重是:" . $weight . "<br />";
echo "平均體重是:" . $avg;
?>
默認情況下,數組下標從0開始。實際上,也可以自己指定,即:自己可以指定方框號內的關鍵字。
此時,遍歷數組需要使用foreach
基本語法:
$arr['logo']="北京";
$arr['abc']=100;
例:
<?php
$arr['logo'] = "www.bianceng.cn";
$arr['abc'] = 123;
foreach ($arr as $key => $val) {
echo $val . '<br />';
}
?>
URL:http://www.bianceng.cn/webkf/PHP/201609/50438.htm