php 遍历mysql数组中_PHP 遍历数组的方法汇总

本文通过实例代码展示了PHP中for、while和foreach遍历数组的性能差异。经过测试,foreach在遍历50000个元素的数组时速度最快,其次是for,而while最慢。尽管while在理论上可能更直接地操作数组指针,但在实际应用中,由于foreach是PHP的内置实现,因此效率更高。结论是,在大多数情况下,foreach不仅简洁,而且在性能上优于while。
摘要由CSDN通过智能技术生成

$fruits= array("apple","orange","banana");

$fruit= current($fruits); //return "apple"

echo $fruit."
";

$fruit= next($fruits); //return "orange"

echo $fruit."
";

$fruit= prev($fruits); //return "apple"

echo $fruit."
";

$fruit= end($fruits); //return "banana"

echo $fruit."
";

?>

显示结果:

apple

orange

apple

banana

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

一般情况下,遍历一个数组有三种方法,for、while、foreach。其中最简单方便的是foreach。下面先让我们来测试一下共同遍历一个有50000个下标的一维数组所耗的时间。

测试环境:

Intel Core Due2 2GHz

2GB 1067MHz DDR3

Mac OS X 10.5.7

Apache 2.0.59

MySQL 5.0.41

PHP 5.2.6

#example8

$arr= array();

for($i= 0; $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

$str= $arr[$i];

}

$time_end= GetRunTime();

$time_used= $time_end- $time_start;

echo 'Used time of for:'.round($time_used, 7).'(s)
';

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)
';

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)
';

?>

测试结果:

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还可以遍历类的属性。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值