创建数组,分别用for/while和foreach遍历,比较他们的不同之处

Original 2019-04-08 09:45:07 275
abstract:<?php //索引数组 //用字面量的方式进行创建:Index $Index = ['a','b','c'];//create //关联数组 $Relation = ['name'=>'Zhang','position'=>'Chin
<?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是专门以键和值为中心,为遍历数组设计的函数。

Correcting teacher:天蓬老师Correction time:2019-04-08 09:46:55
Teacher's summary:每一种循环都有自己的应用场景, 但绝大多数情况 下, 都可以互相转换的, 最灵活最复杂的当属for循环, 不可小看

Release Notes

Popular Entries