<?php //索引数组 //用字面量的方式进行创建:Index $Index = ['a','b','c'];//create //关联数组 $Relation = ['name'=>'Zhang','position'=>'China','skill'=>'code']; //逐个添加的方式创建数组 $Relations=[];//先声明 $Relations['name']='Wang'; $Relations['position']='America'; $Relations['skill']='code'; //for遍历索引数组 $res1='';//res一般是空字符串 for($i=0;$i<count($Index);$i++){ $res1 .=$Index[$i] .','; } echo rtrim($res1,','), '<hr>'; //while循环遍历索引数组 $res2=''; $i=0; while($i<count($Index)){ $res2.=$Index[$i].'*'; $i++; } echo rtrim($res2,'*'),'<hr>'; //foreach循环遍历索引数组 foreach($Relation as $key=>$value){ echo $key,'=>',$value,'<br>'; }
for内部直接比较数组的长度,while常常需要条件判断数组是否执行到最后一个数据。foreach是专门以键和值为中心,为遍历数组设计的函数。