1. foreach()

foreach()是一个用来遍历数组中数据的最简单有效的方法。
#example1:

<?php
$colors = array('red','blue','green','yellow');
foreach ($colors as $color) {
	echo "Do you like $color? <br />";
}
?>

2. while()

while() 通常和 list(),each()配合使用。
#example2:

<?php
$colors = array('red','blue','green','yellow');

while(list($key,$val) = each($colors)) {
	echo "Other list of $val.<br />";
}
?>

3. for()

#example3:

<?php
$arr = array ("0" => "zero","1" => "one","2" => "two");

for ($i = 0;$i < count($arr); $i++) {
	$str = $arr[$i];
	echo "the number is $str.<br />";
}
?>

=========== 下面来测试三种遍历数组的速度 ===========

<?php
$arr = array();
for($i = 0; $i < 50000; $i++){
$arr[] = $i*rand(1000,9999);
}

function GetRunTime()
{
list($usec,$sec)=explode(" ",microtime());
return ((float)$usec+(float)$sec);
}
######################################
$time_start = GetRunTime(); 

for($i = 0; $i < count($arr); $i++){
$str = $arr[$i];
} 

$time_end = GetRunTime();
$time_used = $time_end - $time_start;

echo 'Used time of for:'.round($time_used, 7).'(s)<br /><br />';
unset($str, $time_start, $time_end, $time_used);
######################################
$time_start = GetRunTime();

while(list($key, $val) = each($arr)){
$str = $val;
}
$time_end = GetRunTime();
$time_used = $time_end - $time_start;
echo 'Used time of while:'.round($time_used, 7).'(s)<br /><br />';
unset($str, $key, $val, $time_start, $time_end, $time_used);
######################################
$time_start = GetRunTime();
foreach($arr as $key => $val){
$str = $val;
}

$time_end = GetRunTime();
$time_used = $time_end - $time_start;
echo 'Used time of foreach:'.round($time_used, 7).'(s)<br /><br />';

?>

测试结果:
Used time of for:0.0136571(s)

Used time of while:0.037991(s)

Used time of foreach:0.0048609(s)
结果表明,对于遍历同样一个数组,foreach速度最快,最慢的则是while。

» 版权所有:YaoLei's Blog » PHP 遍历数组的方法
» 本文链接:https://www.yaolei.info/archives/57