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
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
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-2021 The PHP Group
All rights reserved.
Last updated: Mon Sep 20 03:03:36 2021 UTC