PHP数组

PHP数组
1 创建数组array();
比如:$cars=array("Volvo","BMW","Toyota");
或者:$cars=["Volvo","BMW","Toyota"];
高版本的提倡用[]
空数组:$arr = array(); 或者 $arr = [];

2 三种数组类型:
数值数组 - 带有数字 ID 键的数组 跟Java普通数组一样
关联数组 - 带有指定的键的数组,每个键关联一个值 类似Java Map
多维数组 - 包含一个或多个数组的数组

数值数组:
$cars=array("Volvo","BMW","Toyota");
或者:$age=array(0=>"35",1=>"37",2=>"43");
或者:
$cars[0]="Volvo";
$cars[1]="BMW";
$cars[2]="Toyota";

关联数组:
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
或者:
$age['Peter']="35";
$age['Ben']="37";
$age['Joe']="43";

3 获得数组长度:count() $i = count($cars);

4 遍历数组:

(1)
<?php
$fruit=array('苹果','香蕉','菠萝');
for($index=0; $index<count($fruit); $index++){
echo '<br>数组第'.$index.'值是:';
}
?>

(2)

<?php
$cars=array("Volvo","BMW","Toyota");
$arrlength=count($cars);

for($x=0;$x<$arrlength;$x++)
{
echo $cars[$x];
echo "<br>";
}
?>

 

(3)
遍历关联数组:
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");

foreach($age as $x=>$x_value)
{
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
?>

 

posted @ 2018-07-31 17:56  kaixinmao1987  阅读(148)  评论(0编辑  收藏  举报