一、定义数组:arry()函数用于创建数组
- 数值数组-带有数字ID键的数组
- 关联数组-带有指定键的数组,每个键关联一个值
- 多维数组-包含一个或多个数组的数组
1、数值数组
(1)、$cars=arry("","BMW","Toyota");
或 $cars[0]="Volvo" $cars[1]="BMW" $cars[2]="Toyota"
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
(2)、获取数组的长度-count()函数
<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars);
?>
运行结果:3
(3)、遍历数值数组
<?php
$cars=arry("Volvo","BMW","Toyota");
$arrlength=count($cars);
for($x=0;$x<$arrlength;$x++){
echo $cars[$x];
echo "<br>"
}
运行结果为:Volvo
BMW
Toyota
2、关联数组
(1)、创建关联数组
$age=arry("Peter"=>"35","Ben"=>"37","Joe"=>"43");
或 $age['Peter']="35" $age['Ben']="37" $age['Joe']="43"
例:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
?>
运行结果为:Peter is 35 years old.
(2)、遍历关联数组
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>
3、多维数组
<?php
// 二维数组:
$cars = array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
);
?>
自动分配ID键
<?php
$sites = array
(
"runoob"=>array
(
"菜鸟教程",
"http://www.runoob.com"
),
"google"=>array
(
"Google 搜索",
"http://www.google.com"
),
"taobao"=>array
(
"淘宝",
"http://www.taobao.com"
)
);
print("<pre>"); // 格式化输出数组
print_r($sites);
print("</pre>");
?>
输出结果:
让我们试着显示上面数组中的某个值:
echo $sites['runoob'][0] . '地址为:' . $sites['runoob'][1];
上面的代码将输出: