Bug #73261 [Nab]: Looping through array with pointer inadvertently breaks array.
| From: | randy at larsongroup dot org | Date: | Thu, 06 Oct 2016 21:23:03 +0000 |
| Subject: | Bug #73261 [Nab]: Looping through array with pointer inadvertently breaks array. | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-204522@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=73261&edit=1
ID: 73261
User updated by: randy at larsongroup dot org
Reported by: randy at larsongroup dot org
Summary: Looping through array with pointer inadvertently
breaks array.
Status: Not a bug
Type: Bug
Package: Arrays related
Operating System: Tested on OSX and Ubuntu 12.04
PHP Version: 5.6.26
Block user comment: N
Private report: N
New Comment:
Sorry. It was an ID10T mistake!
Previous Comments:
------------------------------------------------------------------------
[2016-10-06 21:12:05] nikic@php.net
Please see the red warning box on http://php.net/foreach :)
------------------------------------------------------------------------
[2016-10-06 21:08:37] randy at larsongroup dot org
Description:
------------
When you loop through an array with foreach and set the value as a pointer to the array value then
the last element in the array will be set as a pointer to the second to last element of the array.
Then if you loop through the array a second time you will see that the last value isn't there,
but points to the second to last value.
Test script:
---------------
<?php
$originalArray = array('Thor', 'The Hulk', 'Iron Man');
var_dump($originalArray);
foreach ($originalArray as &$value) {
echo $value."\n";
}
echo "\nSecond time through loop\n";
foreach ($originalArray as $value) {
echo $value."\n";
}
// notice the last element is a pointer which it shouldn't be.
echo "\n".var_dump($originalArray);
Expected result:
----------------
array(3) {
[0]=>
string(4) "Thor"
[1]=>
string(8) "The Hulk"
[2]=>
string(8) "Iron Man"
}
Thor
The Hulk
Iron Man
Second time through loop
Thor
The Hulk
Iron Man
array(3) {
[0]=>
string(4) "Thor"
[1]=>
string(8) "The Hulk"
[2]=>
string(8) "Iron Man"
}
Actual result:
--------------
array(3) {
[0]=>
string(4) "Thor"
[1]=>
string(8) "The Hulk"
[2]=>
string(8) "Iron Man"
}
Thor
The Hulk
Iron Man
Second time through loop
Thor
The Hulk
The Hulk
array(3) {
[0]=>
string(4) "Thor"
[1]=>
string(8) "The Hulk"
[2]=>
&string(8) "The Hulk"
}
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=73261&edit=1