Issues referenced in foreach

Source: Internet
Author: User

I encountered a problem about the PHP foreach reference at work.

Simply put, the following code

 

$arr=array(‘a‘,‘b‘,‘c‘ ,‘d‘);foreach($arr as $k=>&$v){  ........} foreach($arr as $k=>$v){........} print_r($arr);

 

 

The result is

A

B

C

C

 

Refer to this article and this article

After the first foreach traversal, the value of $ V is 'D' and the corresponding key is 3. Note that $ V is referenced here.

When the second foreach traverses the first element, $ v = 'A', then according to the reference, $ arr [3] = 'A'

The value of $ arr is

0

1 B

2 C

3

When traversing the second element, $ v = 'B', then according to the reference, $ arr [3] = 'B'

The value of $ arr is

0

1 B

2 C

3 B

When traversing the third element, $ v = 'C', then according to the reference, $ arr [3] = 'C'

The value of $ arr is

0

1 B

2 C

3 C

 

When traversing the third element, $ v = 'C', then according to the reference, $ arr [3] = 'C'

At this time, the value of $ arr is, and it remains unchanged

0

1 B

2 C

3 C

 

Solution:

After the first foreach, add unset ($ V );

 

 

 

 

 

 

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.