Home > Backend Development > PHP Tutorial > Comparative analysis of PHP one-dimensional array traversal methods

Comparative analysis of PHP one-dimensional array traversal methods

WBOY
Release: 2016-07-25 08:58:54
Original
1154 people have browsed it
  1. //a
  2. $arr=array('a'=>'abc','b'=>123,'c'=>true);
  3. //b
  4. //$arr=range('a','d');
  5. //1
  6. for($i=0;$iecho $arr[$i]. ', ';
  7. echo '
    ';
  8. //2
  9. foreach($arr as $key)
  10. echo "$key, ";
  11. echo '
    ';
  12. // 3
  13. foreach($arr as $key=>$val)
  14. echo "$key-$val, ";
  15. echo '
    ';
  16. //4
  17. reset($arr);
  18. while ($item=each($arr)){
  19. echo $item['key'].'-'.$item['value'].', ';
  20. }
  21. echo '
    ';
  22. //5
  23. reset($arr);
  24. while(list($key,$val)=each($arr)){
  25. echo "$key-$val, ";
  26. }
  27. echo '
    ';
  28. ?>
Copy code

Code description:

Statement a $arr=array('a'=>'abc','b'=>123,'c'=>true); Initialize $arr to get the numeric index array, output: , , , abc, 123, 1, a-abc, b-123, c-1, a-abc, b-123, c-1, a-abc, b-123, c-1, use statement b $arr=range('a','d'); to initialize $arr to get the associative array, output: a, b, c, d, a, b, c, d, 0-a, 1-b, 2-c, 3-d, 0-a, 1-b, 2-c, 3-d, 0-a, 1-b, 2-c, 3-d, The for loop only has limited numeric indexes; after the for and foreach traversal, the data does not need to be reset() to be available for the next traversal, while the each method does.

The above is the entire content of today’s PHP tutorial. I hope it will help you master the method of PHP array traversal. Programmer’s Home, I wish you all the best in your study and progress.



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template