php中数组分为:索引数组和关联数组;
索引数组:数组的索引值是整数,以0开始,通过位置来标识的时候使用索引数,下标从0开始;
关联数组:以字符串作为索引,关联数组更像操作表,索引值为列名,用于访问列的数据
key-value
数组的定义:(两种)
<?php //数组的定义 /* $arr1[0] = "PHP"; $arr1[1] = "MySQL"; $arr1[2] = "Apache"; $arr1[3] = "Linux"; $arr1[] = "PHP"; $arr1[] = "MySQL"; $arr1[] = "Apache"; $arr1[] = "Linux"; */ //关联数组的直接定义 $arr1["brand"] = "iphone5"; $arr1["os"] = "ios"; $arr1["price"] = 4980; //打印数组,print_r print_r($arr1); ?>
<?php //使用array语句来定义数组 $arr1 = array("PHP","MySQL","Apache","Linux"); $arr2 = array( "brand" => "Lumia 900", "os" => "wp8", "price" => 4700 ); echo "<pre>"; print_r($arr2); echo "</pre>"; ?>
数组的遍历:
数组的遍历分为三种,for、foreach、while+list+each
for有局限性,只能遍历关联数组;
<?php // 数组的遍历 $arr1 = array(2,3,4,5,6,7); $arr2 = array( "brand" => "Lumia 900", "os" => "wp8", "price" => 4700 ); //不推荐$i < count($arr1) $len = count($arr2); for($i = 0; $i < $len; $i++){ echo $arr2[$i]."<br />"; } ?>
foreach几乎专门为数组量身定制
1、foreach($arr as $val)
{echo $val.'<br/>';}
2、foreach($arr as $key =>$value)
{echo $key.='='.$value.'<br/>';}
<?php
//foreach 的用法
$arr2 = array(
"brand" => "Lumia 900",
"os" => "wp8",
"price" => 4700
);
$arr1 = array("PHP","MySQL","Apache","Linux");
foreach($arr1 as $key => $val){
echo $key."=".$val."<br />";
}
?>
<?php //while+ list + each $arr1 = array( "brand" => "Lumia 900", "os" => "wp8", "price" => 4700 ); echo "<pre>"; print_r(each($arr1)); echo "</pre>"; list($k,$v) = each($arr1); echo $k."<br />"; echo $v."<br />"; /* while(list($k,$v) = each($arr1)){ echo $k ."=".$v."<br />"; */ } ?>
while+list+each:使用起来比较麻烦,不建议;list是种结构,只针对索引有效,仅能用于数字索引的数组并假定数字索引从0开始
除非数组是被引用,foreach所操作的是指定数组的一个拷贝,而不是该数组本身,在php里数组是通过值传递,对象是引用传值;