Reference in php foreach Loop

Source: Internet
Author: User

This article introduces the reference problem analysis and precautions in the php foreach loop. I hope this article will be helpful to you.


Example

The Code is as follows: Copy code

<? Php
$ Array = array ('A', 'B', 'C', 'D ');
Foreach ($ array as $ key => $ val ){
// Do something
}
Echo $ val; // Output d
Echo $ kay; // output 3
$ Val = 'E ';
Print_r ($ array); // output Array ([0] => a [1] => B [2] => c [3] => d)
?>

In a foreach loop, $ key and $ val variables are not automatically released after the loop ends. The value is retained.

When foreach is referenced, the following situations may occur.

The Code is as follows: Copy code

<? Php
$ Array = array ('A', 'B', 'C', 'D ');
Foreach ($ array as $ key =>&$ val) {// use reference
// Do something
}
Echo $ val; // Output d
Echo $ kay; // output 3
$ Val = 'E ';
Print_r ($ array); // output Array ([0] => a [1] => B [2] => c [3] => e)
?>

When the $ val variable is used and referenced, after the foreach loop is executed, $ val points to the same memory address as $ arrar [3.
After the foreach loop ends, the $ val variable still exists. Therefore, changing the value of $ val after the foreach loop ends is equivalent to changing the value of $ arrar [3.

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.