Bug #66859 [Nab]: Variable re-use in for loop causes corruption

From: Date: Mon, 10 Mar 2014 01:00:42 +0000
Subject: Bug #66859 [Nab]: Variable re-use in for loop causes corruption
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-184670@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=66859&edit=1

 ID:                 66859
 User updated by:    jake_hotson at hotmail dot com
 Reported by:        jake_hotson at hotmail dot com
 Summary:            Variable re-use in for loop causes corruption
 Status:             Not a bug
 Type:               Bug
 Package:            Scripting Engine problem
 Operating System:   Win XP Pro
 PHP Version:        Irrelevant
 Block user comment: N
 Private report:     N

 New Comment:

Thanks.  Now found an almost-identical example as the first user-contributed item at http://www.php.net/manual/en/language.references.php
(and upvoted it).

I blame my C/C++/Java background as the behaviour did seem so bizarre that it couldn't be by
design (philosophically it wasn't, though logically it was).  Sorry for raising a non-bug.

Close.  Explanation accepted.


Previous Comments:
------------------------------------------------------------------------
[2014-03-09 06:48:31] 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

References. After the first loop $fruit is still a reference and that means attempting to change its
value will affect whatever it was a reference to as well. In this situation you'll experience
that as showing "<key> is <previous key>" in the last iteration.

unset($fruit) after the first loop.

------------------------------------------------------------------------
[2014-03-09 06:14:04] jake_hotson at hotmail dot com

Description:
------------
PHP ver 5.4.8.  Unable to test in 5.5.10 as seems incompatible with Apache 2.4.7.

Script below says that orange is an apple, but if the first foreach is commented out it correctly
says that it is fruity.

Test script:
---------------
        $fruits = array(
          'apple' => 'fruity',
          'orange' => 'fruity',
        );
        foreach ($fruits as &$fruit) {
        }
        foreach ($fruits as $fruit => $description) {
          echo "$fruit is $description<br />\n";
        }


Expected result:
----------------
apple is fruity
orange is fruity

Actual result:
--------------
apple is fruity
orange is apple


------------------------------------------------------------------------



-- 
Edit this bug report at https://bugs.php.net/bug.php?id=66859&edit=1


Thread (3 messages)

« previous php.bugs (#184670) next »