php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #42839 Assigning array values inside foreach and array pointer
Submitted: 2007-10-03 14:37 UTC Modified: 2007-11-13 11:46 UTC
Votes:2
Avg. Score:5.0 ± 0.0
Reproduced:2 of 2 (100.0%)
Same Version:2 (100.0%)
Same OS:2 (100.0%)
From: denis at edistar dot com Assigned:
Status: Not a bug Package: Scripting Engine problem
PHP Version: 5.2.4 OS: Linux
Private report: No CVE-ID: None
 [2007-10-03 14:37 UTC] denis at edistar dot com
Description:
------------
In PHP 5.2.4 when I set array values inside a foreach, the array pointer is moved to the second element of the array or, better, to the element after the first modified element of the array.

In PHP 5.2.3 the array pointer was not moved.

Moreover this does not happen if i assign the array elements outside the foreach.

Reproduce code:
---------------
$parameters = array(
        'a' => 1,
        'b' => 2,
        'c' => 3,
        'd' => 4
);
echo "\$parameters key before foreach: " . key($parameters) . "\n";
foreach($parameters as $key => $value) {
        $parameters[$key] = "s" . $value;
}
echo "\$parameters key after foreach: " . key($parameters) . "\n";

echo "\$parameters key before foreach: " . key($parameters) . "\n";
$parameters['a'] = "s" . 1;
$parameters['b'] = "s" . 2;
$parameters['c'] = "s" . 3;
$parameters['d'] = "s" . 4;
echo "\$parameters key after foreach: " . key($parameters) . "\n";


Expected result:
----------------
$parameters key before foreach: a
$parameters key before foreach: a

$parameters key before foreach: a
$parameters key before foreach: a

Actual result:
--------------
$parameters key before foreach: a
$parameters key before foreach: b

$parameters key before foreach: a
$parameters key before foreach: a

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-11-12 11:10 UTC] denis at edistar dot com
The problem still persist. Using the example now the results are:

$parameters key before foreach: a
$parameters key after foreach: b
$parameters key before foreach: b
$parameters key after foreach: b

and not the expected results:

$parameters key before foreach: a
$parameters key after foreach: a
$parameters key before foreach: a
$parameters key after foreach: a
 [2007-11-13 11:46 UTC] tony2001@php.net
Array internal pointer position after foreach() depens on a dozen parameters and in general is undefined.

The newer version of the docs makes it clear:
--
Note: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
http://docs.php.net/foreach
--
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Fri May 02 16:01:29 2025 UTC