php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #73261 Looping through array with pointer inadvertently breaks array.
Submitted: 2016-10-06 21:08 UTC Modified: 2016-10-06 21:23 UTC
From: randy at larsongroup dot org Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.6.26 OS: Tested on OSX and Ubuntu 12.04
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: randy at larsongroup dot org
New email:
PHP Version: OS:

 

 [2016-10-06 21:08 UTC] 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"
}

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-10-06 21:12 UTC] nikic@php.net
-Status: Open +Status: Not a bug
 [2016-10-06 21:12 UTC] nikic@php.net
Please see the red warning box on http://php.net/foreach :)
 [2016-10-06 21:23 UTC] randy at larsongroup dot org
Sorry. It was an ID10T mistake!
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Tue Jul 15 01:01:35 2025 UTC