<?php $a = array('a','b','c'); print_r($a); ?>
输出结果:Array ( [0] => a [1] => b [2] => c )
当给一个数组没有分配键的情况下,会自动从0开始分配
<?php $arr = array('a','b','c','d'); $a = 0; while($a<=3){ echo $arr[$a],'<br>'; $a = $a + 1; } ?>
关联数组不能用循环
接下来就引出一个专门循环数组的,foreach
<?php foreach ($variable as $key => $value){ # code... } ?>
案例
<?php $arr2 = array('name'=>'zhangsan','age'=>23,'gender'=>'nv'); foreach ($arr2 as $key => $value){ echo $value,'<br>'; } ?>
输出结果:
zhangsan
23
nv
<?php $arr2 = array('name'=>'zhangsan','age'=>23,'gender'=>'nv'); foreach ($arr2 as $key => $value){ echo $key,':',$value,'<br>'; } ?>
输出结果:
name:zhangsan
age:23
gender:nv
<?php $arr2 = array('name'=>'zhangsan','age'=>23,'gender'=>'nv'); foreach ($arr2 as $key){ echo $key,'<br>'; } ?>
当as后面只跟一个变量的话,无论你命名这个变量,都是指向值
输出结果:
zhangsan
23
nv
array_keys 返回数组中所有的键名,但是foreach更加好,想要key就有key,想要value就有value
<?php $arr2 = array('name'=>'zhangsan','age'=>23,'gender'=>'nv'); print_r(array_keys($arr2)); ?>