遍历数组的三种方式: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)

    '
    ;

  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)

    '
    ;

  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)

    '
    ;

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

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

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