Strange foreach reference issue
| From: | Tim Behrendsen | Date: | Sat, 07 Jan 2012 23:29:37 +0000 |
| Subject: | Strange foreach reference issue | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-316213@lists.php.net to get a copy of this message | ||
Hello,
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.
<?php
$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) {
print "Title A $idx: {$row['Title']}\n";
}
print " Rows are now: " . print_r($row_list, true);
foreach ($row_list as $idx => $row) {
print "Title B $idx: {$row['Title']}\n";
}
?>
When you run the program, it gives the following output:
------------------------------------------
Rows at start: Array
(
[0] => Array
(
[Title] => Title #1
)
[1] => Array
(
[Title] => Title #2
)
[2] => Array
(
[Title] => Title #3
)
)
Title A 0: Title #1
Title A 1: Title #2
Title A 2: Title #3
Rows are now: Array
(
[0] => Array
(
[Title] => Title #1
)
[1] => Array
(
[Title] => Title #2
)
[2] => Array
(
[Title] => Title #3
)
)
Title B 0: Title #1
Title B 1: Title #2
Title B 2: Title #2
------------------------------------------
Note that the second foreach repeats the second row, even though the index is correct and the print_r shows things as correct.
Now, if you change the name of the reference variable from '$row' to '$rowx' (for example), things will work. So clearly there's some issue with $row being previously used as a reference that's "contaminating" the subsequent use of $row in the foreach. If there's some logic to this, it's escaping me.
Any insight on this would be appreciated.
Regards,
Tim Behrendsen