PHP 4 引入了 foreach 结构,用foreach可以帮助我们简单遍历数组,foreach 仅能用于数组,当用于其它数据类型或者一个未初始化的变量时会产生错误。
其用法为:
foreach(数组 as 键 => 值){//循环体}
当数组只有值,没有键时,只需(数组 as 值),把键给删除就行了
<?phpheader('content-type:text/html;charset=utf-8');$person=array('DL_one',18,'man');foreach($person as $value){echo $value,'<br>';}
?>
<?phpheader('content-type:text/html;charset=utf-8');$person=array('name'=>'DL_one','age'=>18,'sex'=>'man');foreach($person as $key=>$value){echo $key,'---',$value,'<br>';}
?>
当输出二维数组时:
<?phpheader('content-type:text/html;charset=utf-8');$person = array(array('id'=>'11','name'=>'Tom'),array('id'=>'22','name'=>'Mary'),array('id'=>'33','name'=>'Peter'),array('id'=>'44','name'=>'Jack'));foreach($person as $key=>$value){echo $value['id'],'---',$value['name'],'<br>';}
?>
其过程是: