遍历数组的三种方式:foreach循环 | while + list + each组合循环 | for循环
<?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 );
}
echo '#############first method for#################';
$time_statr = getRunTime();
$numc = count( $arr );
for( $i=0;$i<$numc;$i++ ){
$str = $arr[$i];
}
$time_end = getRunTime();
$time_used = $time_end-$time_statr;
echo 'Used time of for:'.round($time_used, 7).'(s)<br /><br />';
unset( $str,$time_statr,$time_end,$time_used );
echo '#############second method (while list each)#################';
$time_statr = getRunTime();
while( list( $key,$value ) = each( $arr ) ){
$str = $value;
}
$time_end = getRunTime();
$time_used = $time_end-$time_statr;
echo 'Used time of while:'.round($time_used, 7).'(s)<br /><br />';
unset($str, $key, $val, $time_start, $time_end, $time_used);
echo '#############third method foreach#################';
$time_statr = getRunTime();
foreach( $arr as $key=>$value ){
$str = $value;
}
$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.003757(s)
######################################Used time of while:0.0147378(s)
######################################Used time of foreach:0.001509(s)