|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2016-11-30 09:09 UTC] dorin dot marcoci at gmail dot com
Description:
------------
Script below output A A instead of A B.
Is this as designed?
If I do unset($Item) before second foreach then it works as expected.
Test script:
---------------
<?php
$Items = [['Code' => 'A'], ['Item' => 'B']];
foreach ($Items as &$Item)
$Item['Hash'] = rand(1, 10);
foreach ($Items as $Item)
echo ' '.$Item['Code'];
Expected result:
----------------
A B
Actual result:
--------------
A A
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2026 The PHP GroupAll rights reserved. |
Last updated: Wed Oct 07 07:00:01 2026 UTC |
<?php $A = 'one'; $B = 'two'; $H = [$A, $B]; foreach ($H as &$C); foreach ($H as $C) echo ' '.$C; echo "\n$A $B\n" . join(" ", $H); ?> Is equivalent to <?php $A = 'one'; $B = 'two'; $H = [$A, $B]; for($i = 0; $i < count($H); $i++) { $C = &$H[$i]; } for($i = 0; $i < count($H); $i++) { $C = $H[$i]; echo ' '.$C; } echo "\n$A $B\n" . join(" ", $H); ?> And is therefore equivalent to: <?php $A = 'one'; $B = 'two'; $H = [$A, $B]; $C = &$H[0]; $C = &$H[1]; $C = $H[0]; echo ' '.$C; $C = $H[1]; echo ' '.$C; echo "\n$A $B\n" . join(" ", $H); ?> So with "$C = &$H[1];" $C is set as a reference to the 1st element of H. Then the value of the 0th element of $H is assigned to it (and therefore, by reference, the 1st element of $H). Then the 1st element of $H (which now has the same value as the 0th element) is assigned to it (which has no effect because the 1st element of H already has the same value as the 1st element of H).