php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #76336 array foreach by reference will change the last value
Submitted: 2018-05-13 15:27 UTC Modified: 2018-05-13 16:10 UTC
From: janpoem at gmail dot com Assigned:
Status: Not a bug Package: PHP Language Specification
PHP Version: 7.0.30 OS: windows, ubuntu
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 this is not your bug, you can add a comment by following this link.
If this is your bug, but you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: janpoem at gmail dot com
New email:
PHP Version: OS:

 

 [2018-05-13 15:27 UTC] janpoem at gmail dot com
Description:
------------
Foreach an array by reference will change the last value (previous).

Test script:
---------------
<?php

$array = [
	['a' => 'aa'],
	['b' => 'bb'],
	['c' => 'cc'],
	['d' => 'dd'],
	['e' => 'ee'],
	['f' => 'ff'],
];

foreach ($array as & $item) {
}

var_dump($array);
/*

here will output:

array(6) {
  [0]=>
  array(1) {
    ["a"]=>
    string(2) "aa"
  }
  [1]=>
  array(1) {
    ["b"]=>
    string(2) "bb"
  }
  [2]=>
  array(1) {
    ["c"]=>
    string(2) "cc"
  }
  [3]=>
  array(1) {
    ["d"]=>
    string(2) "dd"
  }
  [4]=>
  array(1) {
    ["e"]=>
    string(2) "ee"
  }
  [5]=>
  &array(1) {
    ["f"]=>
    string(2) "ff"
  }
}

*/

echo '=====================================', PHP_EOL;

foreach ($array as $item) {
	var_dump($item);
}

/*
array(1) {
  ["a"]=>
  string(2) "aa"
}
array(1) {
  ["b"]=>
  string(2) "bb"
}
array(1) {
  ["c"]=>
  string(2) "cc"
}
array(1) {
  ["d"]=>
  string(2) "dd"
}
array(1) {
  ["e"]=>
  string(2) "ee"
}
array(1) {
  ["e"]=>
  string(2) "ee" // => this one was changed.
}
*/


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2018-05-13 16:10 UTC] peehaa@php.net
-Status: Open +Status: Not a bug
 [2018-05-13 16:10 UTC] peehaa@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

In specific the part about foreach and using references http://php.net/manual/en/control-structures.foreach.php
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 09:01:26 2024 UTC