php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #51951 foreach-statement manipulates array (in a special case)
Submitted: 2010-05-30 20:29 UTC Modified: 2010-05-30 20:34 UTC
Votes:1
Avg. Score:4.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: c336848 at owlpic dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: Irrelevant OS: Linux
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: c336848 at owlpic dot com
New email:
PHP Version: OS:

 

 [2010-05-30 20:29 UTC] c336848 at owlpic dot com
Description:
------------
The test script manipulates the last entry of $my_array instead of all or leaving everything as it is.

my php version: 5.2.10

Test script:
---------------
<?
$my_Array[] = 'a';
$my_Array[] = 'b';
$my_Array[] = 'c';
$my_Array[] = 'd';

echo '<pre>1:' . print_r($my_Array, true) . '</pre>';

foreach($my_Array as &$value){
}

echo '<pre>2:' . print_r($my_Array, true) . '</pre>';

foreach($my_Array as $value){
}

echo '<pre>3:' . print_r($my_Array, true) . '</pre>';
?>

Expected result:
----------------
3:Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
)

Actual result:
--------------
3:Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => c
)

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-05-30 20:34 UTC] pajoye@php.net
-Status: Open +Status: Bogus
 [2010-05-30 20:34 UTC] pajoye@php.net
The last loop modifies the $value from the 1st one, which is a reference. Simply do:  foreach($my_Array as $val)to see the difference.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Mon Aug 18 09:00:02 2025 UTC