Where to use references in a foreach loop in PHP

Source: Internet
Author: User
Tags explode foreach loop in php

Found an error-prone, but do not understand the principle of the explanation does not understand the problem, encounter similar problems of friends can refer to.

Copy the Code code as follows:


foreach ($array as & $v) {
$v = explode ('/', $v);
}
foreach ($array as $v) {
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 $v, the output of the loop to the last is the penultimate element, not the last

To write like this.

Copy the Code code as follows:


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


Or the first cycle of this.

Copy the Code code as follows:


foreach ($array as $k = = $v) {
$array [$k] = explode ('/', $r);
}


Say the principle.
The first loop uses the reference, and after the loop is finished, $v refers to the last element of the $array array, and when the second loop is started, the $v variable is assigned a new value each time the loop is called, and in PHP, if a memory space is referenced, the value of the memory space is changed directly when it is changed. , 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, when the second loop is changed to the value of the second element, when the second cycle is reversed, it is changed to the second value of the penultimate element, And the last time you loop, the value of enlightenment must be the second-lowest value.
Of course, if PHP's for loop has scope, this problem does not occur .....

This article is from the "Half City" blog, please be sure to keep this source http://vabc1314.blog.51cto.com/2164199/1663122

Where to use references in a foreach loop in PHP

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.