第一、foreach()
foreach()是一个用来遍历数组中数据的最简单有效的方法。
?
1
2
3
4
5
6
显示结果:
?
1
2
3
4
this site url is aaa
this site url is bbb
this site url is ccc
this site url is ddd
第二、while() 和 list(),each()配合使用。
?
1
2
3
4
5
6
显示结果:
?
1
2
3
4
this site url is aaa
this site url is bbb
this site url is ccc
this site url is ddd
第三、for()运用for遍历数组
?
1
2
3
4
5
6
7
显示结果:
?
1
2
3
4
this site url is aaa
this site url is bbb
this site url is ccc
this site url is ddd
有时候有人也在问这几种遍历数组的方法哪个更快捷些呢,下面做个简单的测试就明白了
=========== 下面来测试三种遍历数组的速度 ===========
一般情况下,遍历一个数组有三种方法,for、while、foreach。其中最简单方便的是foreach。下面先让我们来测试一下共同遍历一个有50000个下标的一维数组所耗的时间。
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
$val){
$str= $val;
}
$time_end= getruntime();
$time_used= $time_end- $time_start;
echo 'used time of foreach:'.round($time_used, 7).'(s)
';
?>
测试结果:
?
1
2
3
used time of for:0.0228429(s)
used time of while:0.0544658(s)
used time of foreach:0.0085628(s)
经过反复多次测试,结果表明,对于遍历同样一个数组,foreach速度最快,最慢的则是while。从原理上来看,foreach是对数组副本进行操作(通过拷贝数组),而while则通过移动数组内部指标进行操作,一般逻辑下认为,while应该比foreach快(因为foreach在开始执行的时候首先把数组复制进去,而while直接移动内部指标。),但结果刚刚相反。原因应该是,foreach是php内部实现,而while是通用的循环结构。所以,在通常应用中foreach简单,而且效率高。在php5下,foreach还可以遍历类的属性。
http://www.bkjia.com/phpjc/993431.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/993431.htmltecharticlephp遍历数组的方法汇总 今天有个朋友问我一个问题php遍历数组的方法,告诉她了几个。顺便写个文章总结下,如果总结不全还请朋友们指出...
