Phpforeach looping array method

Source: Internet
Author: User
The foreach statement is used to traverse the array. each time an array is cyclically traversed, the value of the current array element is assigned to the value variable (the array pointer is moved one by one). The syntax is as follows:

The foreach statement is used to traverse the array cyclically. The value of the current array element is assigned to the value variable (the array pointer is moved one by one). The syntax is as follows:

  1. Foreach (array as value)
  2. {
  3. Code to be executed;
  4. }

The following example demonstrates a loop that outputs the value of a given array:

  1.  
  2.  
  3. $ Arr = array ("one", "two", "three ");
  4. Foreach ($ arr as $ value)
  5. {
  6. Echo "value:". $ value ." ";
  7. }
  8. ?>
  9.  
  10.  

The following describes in detail:

  1. Foreach ($ array as & $ row ){
  2. $ Row = explode ('/', $ row );
  3. }
  4. Foreach ($ array as $ row ){
  5. // Do something
  6. }

In this case, a logic error occurs in the second loop. in the second loop, do something outputs $ row, and the output at the end of the loop is the second-to-last element, instead of the last one, write as follows:

  1. Foreach ($ array as & $ row ){
  2. $ Row = explode ('/', $ row );
  3. }
  4. Unset ($ row );
  5. Foreach ($ array as $ row ){
  6. // Do something
  7. }

Or write the code in the first loop as follows:

  1. Foreach ($ array as $ key => $ row ){
  2. $ Array [$ key] = explode ('/', $ row );
  3. }

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.