php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #40065 Problem with foreach and referenced values
Submitted: 2007-01-08 17:42 UTC Modified: 2007-01-08 18:26 UTC
Votes:4
Avg. Score:5.0 ± 0.0
Reproduced:4 of 4 (100.0%)
Same Version:2 (50.0%)
Same OS:3 (75.0%)
From: ugo at iliona dot net Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.2.0 OS: Linux/BSD
Private report: No CVE-ID: None
 [2007-01-08 17:42 UTC] ugo at iliona dot net
Description:
------------
Hello, 

This bug was tried on multiple Unix versions and multiple processors (32/64bits), and multiple PHP5 versions (including 5.2.0), so it seems really to be on the side of PHP.
After using a foreach with a referenced value, and then another foreach (without the referenced value), the original array is broken.
Apparently, the last value of the array takes the value of the n - 1 last value.

I've reduced the problem to its simplest form and attached it to this bug report.

Greeting, 

Ugo PARSI

Reproduce code:
---------------
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
   $value = $value * 2;
}
print_r($arr);
foreach ($arr as $value) {
   $value = $value;
}
print_r($arr);
?>

Expected result:
----------------
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 ) Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )

Actual result:
--------------
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 ) Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 6 )

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-01-08 17:55 UTC] derick@php.net
Please do not submit the same bug more than once. An existing
bug report already describes this very problem. Even if you feel
that your issue is somewhat different, the resolution is likely
to be the same. 

Thank you for your interest in PHP.

,
 [2007-01-08 18:06 UTC] ugo at iliona dot net
Hmmm...
I haven't found a similar open bug in the database (I wouldn't have posted it otherwise), but if you say that it is the same as another one, that's okay for me as long as it is fixed in the next version :)
 [2007-01-08 18:10 UTC] derick@php.net
#29992 and it is not a bug.
 [2007-01-08 18:26 UTC] ugo at iliona dot net
Ok, I see... it's quite logical if foreach behave like this....sorry for the bogus report then...
But, since it's not a bug, that's a hell of nice weird feature :/

It should probably be put in the documentation that foreach doesn't unset/reset it's value(s) variable(s) (since it does this for the it's array pointer, and some languages does this too, it's quite an unpredictable situation)

Thanks anyway and sorry for this report, 

Ugo
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat May 18 17:01:33 2024 UTC