Comparative analysis of php one-dimensional array traversal methods

Source: Internet
Author: User
Comparative analysis of php one-dimensional array traversal methods

  1. //
  2. $ Arr = array ('a' => 'ABC', 'B' => 123, 'C' => true );
  3. // B
  4. // $ Arr = range ('A', 'D ');
  5. // 1
  6. For ($ I = 0; $ I Echo $ 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. ?>

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'); initialize $ arr to get the associated 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 number indexes. after the for and foreach traversal ends, you do not need to perform the reset () operation on the data for the next traversal, and the each method is required.

The above is all the content of today's php Tutorial. I hope to help you master the php array traversal method, programmer's house, and wish you a better learning experience.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.