Two ways to use PHP foreach ____php

Source: Internet
Author: User
Tags php foreach

Preface:

The foreach structure is introduced in PhP4, a simple way to traverse an array. Compared to the traditional for loop, foreach can get the key-value pairs more easily. foreach can only be used for arrays before php5, and after php5, the object can be traversed by foreach. Only the case of traversing an array is discussed in this article.


The first form traverses the given array_expression array.


In each loop, the value of the current cell is assigned to the $value and the pointer inside the array moves forward one step (so the next cell will be taken in the next loop).

The second format does the same thing, except that in addition to the current cell value, the key value is assigned to the variable $key in each loop. Look at the following code:


Key values Here you can understand the array subscript, and the subscript for the element a[2] is 2.

When foreach starts executing, the pointer inside the array automatically points to the first cell. This means that you do not need to call Reset () before the Foreach loop. The while loop needs to be reset. The following two types of code function exactly the same.

1. Loop with while


2. With foreach


Also note that foreach is manipulating a copy of the specified array, not the array itself. Therefore, even if there is a construct of each (), the original array pointer does not change and the value of the array cell is unaffected.

foreach does not support the ability to use "@" to suppress error messages.

foreach is simple, but it may cause unexpected behavior, especially if the code involves references.
Problem:
Copy code code as follows:
$arr = Array (1,2,3);
foreach ($arr as $k => & $v) {
$v = $v * 2;
}
Now $arr are array (2, 4, 6)
foreach ($arr as $k => $v) {
echo "$k", "=>", "$v";
}

First from the simple start, if we try to run the above code, we will find that the final output is 0=>2 1=>4 2=>4.
Why not 0=>2 1=>4 2=>6.
In fact, we can assume that the foreach ($arr as $k => $V) structure implicitly assigns the current ' key ' and current ' value ' of the array to the variable $k and $v. The concrete expansion form is as follows:
Copy code code as follows:
foreach ($arr as $k => $v) {
2 assignment actions implied before user code execution
$v = Currentval ();
$k = Currentkey ();
Continue to run user code
......
}

Based on the above theory, now we re going to analyze the first foreach:
1th cycle, because $v is a reference, so $v = & $arr [0], $v = $v *2 equals $arr[0]*2, so $arr becomes 2,2,3
2nd cycle, $v = & $arr [1], $arr become 2,4,3
3rd cycle, $v = & $arr [2], $arr become 2,4,6
The code then enters the second foreach:
The 1th cycle, the implied operation $v= $arr [0] is triggered, because at this time $v is still $arr[2] reference, that is equivalent to $arr[2]= $arr [0], $arr into 2,4,2
The 2nd cycle, $v = $arr [1], i.e. $arr[2]= $arr [1], $arr into 2,4,4
The 3rd cycle, $v = $arr [2], i.e. $arr[2]= $arr [2], $arr into 2,4,4
OK, the analysis is complete.
How to solve similar problems. The PHP manual has a reminder:
Warning: The $value reference to the last element of the array remains after the Foreach loop. It is recommended that you use unset () to destroy it.
Copy code code as follows:
$arr = Array (1,2,3);
foreach ($arr as $k => & $v) {
$v = $v * 2;
}
Unset ($v);
foreach ($arr as $k => $v) {
echo "$k", "=>", "$v";
}
Output 0=>2 1=>4 2=>6

We can see from this problem that references are likely to be accompanied by side effects. If you do not want the unconscious changes to result in an array content change, it is best to unset these references in time.


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.