Where to use references in the Foreach Loop in PHP _php tips

Source: Internet
Author: User
Tags explode foreach loop in php
Copy Code code as follows:

foreach ($array as & $row) {
$row = explode ('/', $row);
}
foreach ($array as $row) {
Do something
}

So to write, in the second loop there will be a logical error, add the second loop where do something is output $row, the loop to the last time the output is the penultimate element, not the last

To write that.
Copy Code code as follows:

foreach ($array as & $row) {
$row = explode ('/', $row);
}
Unset ($row);
foreach ($array as $row) {
Do something
}

Or the first loop to write that.
Copy Code code as follows:

foreach ($array as $key => $row) {
$array [$key] = explode ('/', $row);
}


say the principle.
The first loop uses the reference, and after the loop ends, the $row refers to the last element of the $array array, and when the second loop is started, $row variable is assigned a new value each time it is in PHP, if a memory space is referenced, So when you change it, you change the value of the memory space directly, that is, when the first loop of the second foreach, the value of the last element of the $array is changed to the value of the first element of the $array, and the second loop is changed to the value of the second element, When the second cycle is reversed, it is changed to the second last element value, and the value of the Enlightenment is necessarily the penultimate value of the second.
Of course, this problem does not occur if the for loop of PHP is scoped ...

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.