Where to use references in a foreach loop in PHP _php tutorial

Source: Internet
Author: User
Tags foreach loop in php
Copy CodeThe code is as follows:
foreach ($array as & $row) {
$row = explode ('/', $row);
}
foreach ($array as $row) {
Do something
}

In this case, in the second loop there will be a logic error, adding the second loop where do something is the output $row, the output of the loop to the last is the penultimate element, not the last

To write like this.
Copy CodeThe code is as follows:
foreach ($array as & $row) {
$row = explode ('/', $row);
}
Unset ($row);
foreach ($array as $row) {
Do something
}

Or the first cycle of this.
Copy CodeThe code is as follows:
foreach ($array as $key = = $row) {
$array [$key] = explode ('/', $row);
}


say the principle.
The first loop uses the reference, and after the loop is finished, $row refers to the last element of the $array array, and when the second loop is started, the $row variable is assigned a new value each time the loop is used, in PHP, if a memory space is referenced, So when changing it is a direct change to the value of this memory space, 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, the second loop, the second element is changed to a value, At the end of the second cycle, it is changed to the value of the second element, and the value of the last loop is necessarily the second value
Of course, if PHP's for loop has scope, this problem does not occur .....

http://www.bkjia.com/PHPjc/322706.html www.bkjia.com true http://www.bkjia.com/PHPjc/322706.html techarticle Copy the code code as follows: foreach ($array as} foreach ($array as $row) {//do something} is written so that a logic error in the second loop is added to the second loop where do something ... /c5>

  • 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.