The PHP foreach () function is only applicable to arrays.

Source: Internet
Author: User
Tags php foreach

This is just a simple way to traverse arrays. The PHP foreach () function can only be used for arrays. An error occurs when you try to use it for another data type or an uninitialized variable. There are two types of syntax. The second type is secondary, but it is the first type of useful extension.

Foreach (array_expression as $ value)
Statement
Foreach (array_expression as $ key => $ value)
Statement

The first format traverses the given array_expression array. In each loop, the value of the current unit is assigned to $ value and the pointer inside the array moves forward (so the next unit will be obtained in the next loop ).

In the second format, only the key names of the current Unit are assigned to the variable $ key in each loop.

Objects may be traversed from PHP 5.

Note: When the PHP foreach () function is executed, the pointer inside the array automatically points to the first unit. This means that you do not need to call reset () before the foreach loop ().

Note: unless the array is referenced, the PHP foreach () function operates on a copy of the specified array rather than the array itself. Therefore, the array pointer is not changed by the each () structure, and the modification to the returned array unit does not affect the original array. However, the internal pointer of the original array does move forward when processing the array. Assuming that the foreach loop is running till the end, the internal pointer of the original array points to the end of the array.

Since PHP 5, you can easily add & before $ value to modify the array unit. This method will assign values by reference instead of copying a value.

 
 
  1. < ?php   
  2. $arr = array(1, 2, 3, 4);   
  3. foreach ($arr as &$value) {   
  4. $value = $value * 2;   
  5. }   
  6. // $arr is now array(2, 4, 6, 8)   
  7. ?>  

The PHP foreach () function is available only when the retrieved array can be referenced (for example, a variable ).


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.