数组定义
<body> <?php $arr=array();//定义空数组 $arr1=array(1,2,3,2,2);//数组赋值,索引从0开始 ?> </body>
关联数组
<body> <?php $arr2=array("code"=>"p001","name"=>"张三");//索引是code的值为p001,索引为name的值为张三 var_dump($arr2); ?> </body>
赋值定义数组
<body> <?php $arr[0]="张三"; $arr[1]="李四"; var_dump($arr); ?> </body>
array (size=2)
0 => string '张三' (length=6)
1 => string '李四' (length=6)
遍历数组
1、for循环遍历(只能遍历索引数组)
<body> <?php $arr=array("p001","张三",1,"n001","1988-2-3"); for($i=0;$i<count($arr);$i++){ echo $arr[$i]."<br>"; // 哪个都行 //echo "{$arr[$i]}<br>"; } ?> </body>
2、foreach遍历 (没有限制)
<body> <?php $arr=array("p001","张三",1,"n001","1988-2-3"); foreach($arr as $v){ echo "[$v]<br>"; }//数组取值 ?> </body>
<body> <?php $arr=array("p001","张三",1,"n001","1988-2-3"); foreach($arr as $k=>$v){ echo "[$k-$v]<br>"; }//取索引和值 ?> </body>
3、函数配合遍历数组
list()和each()
<body> <?php $arr=array("p001","张三",1,"n001","1988-2-3"); $a= each($arr); var_dump($a);//执行一次取一次(从索引0到最后) //取出数组当前指针指向元素的内容交给一个数组 ?> </body>
<body> <?php $arr=array("p001","张三",1,"n001","1988-2-3"); list($a,$b,$c)=$arr;//将数组的元素赋值给一组变量,按顺序从索引0开始 var_dump(list($a,$b,$c)=$arr); ?> </body>
<body> <?php $arr=array("p001","张三",1,"n001","1988-2-3"); while(list($k,$v)=each($arr)){ echo"{$k}-{$v}<br>"; }//$k索引,$v值 each($arr)取出每个索引和值 ?> </body>
4、指针遍历
key()取当前指针指向元素的索引
current()取当前指针指向元素的值
next()指针下调一个
prev()指针上调一个
end()指针指向最后一个
reset()指针充值指向第一个
<body> <?php $arr=array("p001","张三",1,"n001","1988-2-3"); do{ echo key($arr);//取索引 echo current($arr);//取值 }while(next($arr))//先执行在条件然后在执行 ?> </body>
5、二维数组
<body> <?php $arr=array( array(1,2,3), array(4,5,6), array(7,8,9) ); echo$arr[1][1];//二维数组取值 ?> </body>
遍历二维数组
<body> <?php $arr=array( array(1,2,3), array(4,5,6), array(7,8,9) ); foreach($arr as $v){ echo"{$v[0]}-{$v[1]}-{$v[2]}<br>"; } ?> </body>
<body> <?php $arr=array( array(1,2,3), array(4,5,6), array(7,8,9) ); foreach($arr as $v){ foreach($v as $v1){ echo $v1; } }//foreach嵌套 ?> </body>
123456789
<?php $arr=array( array("n001","汉族"), array("n002","回族"), array("n003","满族"), array("n004","维吾尔族"), ); echo"<select>"; foreach($arr as $v){ echo"<option value='{$v[0]}'>{$v[1]}</option>"; } echo"</select>" ?>
数组常用函数
in_array()判断某个值是否在数组中存在
array
<body> <?php $arr=array(1,2,2,3,4,5); var_dump(in_array(6,$arr)); ?> </body>
存在返回true 不存在false
array_reverse()反转数组
<body> <?php $arr=array(1,2,2,3,4,5); var_dump(array_reverse($arr)); ?> </body>
array_unipue()去重
<body> <?php $arr=array(1,2,2,3,4,5); var_dump(array_unique($arr)); ?> </body>
unset($arr[1])删除数组元素
array_values()重新索引(删除数值后)
<body> <?php $arr=array(1,2,2,3,4,5); unset($arr[2]); var_dump(array_values($arr)) ?> </body>
array_push(数组,“值”) 在数组最后追加元素
<body> <?php $arr=array(1,2,2,3,4,5); array_push($arr,"100"); var_dump($arr) ?> </body>