php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #73160 foreach var reference incorrect last entry value
Submitted: 2016-09-24 09:38 UTC Modified: 2016-09-24 09:58 UTC
From: florian dot bailly at gmx dot com Assigned:
Status: Not a bug Package: *General Issues
PHP Version: 7.1.0RC2 OS: Mac OSX / Unix
Private report: No CVE-ID: None
 [2016-09-24 09:38 UTC] florian dot bailly at gmx dot com
Description:
------------
The first foreach changes the value by reference of each entry by adding the digit "2".

The next foreach dumps each key with its entry. We can see that the last entry is equal to "titi2" and not "tutu2" (so it appears to be equal to the previous entry).

The last commented out foreach demonstrates that if the var used for the entry is different ($val <> $val2), then there's no bug. But you must comment out the second foreach first.


Test script:
---------------
<?php
$a = [
  'toto',
  'titi',
  'tutu',
];

foreach ($a as $key => &$val)
    $val .= '2';

foreach ($a as $key => $val)
    var_dump($key, $val);

// foreach ($a as $key => $val2)
//     var_dump($key, $val2);


Actual result:
--------------
int(0)
string(5) "toto2"
int(1)
string(5) "titi2"
int(2)
string(5) "titi2"

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2016-09-24 09:58 UTC] requinix@php.net
-Status: Open +Status: Not a bug
 [2016-09-24 09:58 UTC] requinix@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

Please red the big red warning in the documentation.
http://php.net/manual/en/control-structures.foreach.php
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Mon Jul 14 21:01:33 2025 UTC