扫码一下
查看教程更方便
创建名为 $cars 的数值数组,赋三个元素给它,并打印包含数组值的文本:
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
执行结果
I like Volvo, BMW and Toyota.
array() 函数用于创建数组。
在 PHP 中,有三种类型的数组:
数值数组的语法:
array(value1,value2,value3,etc.);
关联数组的语法:
array(key=>value,key=>value,key=>value,etc.);
参数 | 描述 |
---|---|
key | 规定键名(数值或字符串)。 |
value | 规定键值。 |
#1 创建名为 $age 的关联数组:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
执行结果
Peter is 35 years old.
#2 遍历和打印数值数组的值:
<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>
执行结果
Volvo
BMW
Toyota
#3 遍历和打印关联数组的值:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
执行结果
Key=Peter, Value=35
Key=Ben, Value=37
Key=Joe, Value=43
#4 创建多维数组:
<?php
// 一个二维数组
$cars=array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
);
?>
执行结果
Array
(
[0] => Array
(
[0] => Volvo
[1] => 100
[2] => 96
)
[1] => Array
(
[0] => BMW
[1] => 60
[2] => 59
)
[2] => Array
(
[0] => Toyota
[1] => 110
[2] => 100
)
)