什么是数组?
数组是特殊的变量,它可以同时保存一个以上的值。
在 PHP 中创建数组
array();
在 PHP 中,有三种数组类型:
- 索引数组 - 带有数字索引的数组
- 关联数组 - 带有指定键的数组
- 多维数组 - 包含一个或多个数组的数组
PHP 索引数组
<?php
$cars=array("porsche","BMW","Volvo");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
遍历索引数组
如需遍历并输出索引数组的所有值,您可以使用 for 循环,就像这样:
实例
<?php
$cars=array("porsche","BMW","Volvo");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++) {
echo $cars[$x];
echo "<br>";
}
?>
PHP 关联数组
<?php
$age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47");
echo "Elon is " . $age['Elon'] . " years old.";
?>
遍历关联数组
如需遍历并输出关联数组的所有值,您可以使用 foreach 循环,就像这样:
实例
<?php
$age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47");
foreach($age as $x=>$x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>