继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

PHP数组遍历的方法测试

关注TA
已关注
手记
粉丝
获赞

遍历数组的三种方式:foreach循环 | while + list + each组合循环 | for循环

  1. <?php

  2. //循环数组方法

  3. $arr = array();

  4. for( $i=0;$i<50000;$i++ ){

  5.    $arr[] = $i*rand(1000,9999);//随机整数

  6. }

  7. function getRunTime(){

  8.    list( $usec,$sec ) = explode(" ",microtime());

  9.    return ( (float)$usec+(float)$sec );

  10. }

  11. echo '#############first method for#################';

  12. $time_statr = getRunTime();

  13. $numc = count( $arr );

  14. for( $i=0;$i<$numc;$i++ ){

  15.    $str = $arr[$i];

  16. }

  17. $time_end = getRunTime();

  18. $time_used = $time_end-$time_statr;

  19. echo 'Used time of for:'.round($time_used, 7).'(s)<br /><br />';

  20. unset( $str,$time_statr,$time_end,$time_used );

  21. echo '#############second method (while list each)#################';

  22. $time_statr = getRunTime();

  23. while( list( $key,$value ) = each( $arr ) ){

  24.    $str = $value;

  25. }

  26. $time_end = getRunTime();

  27. $time_used = $time_end-$time_statr;

  28. echo 'Used time of while:'.round($time_used, 7).'(s)<br /><br />';

  29. unset($str, $key, $val, $time_start, $time_end, $time_used);

  30. echo '#############third method foreach#################';

  31. $time_statr = getRunTime();

  32. foreach( $arr as $key=>$value ){

  33.    $str = $value;

  34. }

  35. $time_end = getRunTime();

  36. $time_used = $time_end-$time_start;

  37. echo 'Used time of foreach:'.round($time_used, 7).'(s)<br /><br />';

  38. ######################################Used time of for:0.003757(s)

  39. ######################################Used time of while:0.0147378(s)

  40. ######################################Used time of foreach:0.001509(s)


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP