Re: Strange foreach reference issue
| From: | Tim Behrendsen | Date: | Sun, 08 Jan 2012 00:30:07 +0000 |
| Subject: | Re: Strange foreach reference issue | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-316216@lists.php.net to get a copy of this message | ||
On 1/7/2012 4:18 PM, Matijn Woudt wrote:
On Sun, Jan 8, 2012 at 12:29 AM, Tim Behrendsen<tim@behrendsen.com> wrote:When you use an ampersand on the variable, that creates a reference to the array elements, allowing you to potentially change the array elements themselves (which I'm not doing here). http://www.php.net/manual/en/control-structures.foreach.php I do notice in the manual that it says, "Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset()." But that doesn't really explain why it contaminates the next foreach loop in such an odd way. You would think that the $row in the second loop would be assigned a non-reference value. TimHello, This sure looks like a bug, but maybe there's some subtlety going on that I don't understand, so I would appreciate some insight. After much debugging, I tracked down a bug in my code to this test program. My PHP version is 5.3.3, running under Fedora Linux. <?phpWhy is there an '&' before $row here? That seems like the problem to me.. Matijn$row_list = array( array( 'Title' => 'Title #1', ), array( 'Title' => 'Title #2', ), array( 'Title' => 'Title #3', ) );print " Rows at start: " . print_r($row_list, true); foreach ($row_list as $idx => &$row) {