Bug #67916 [Opn->Nab]: Reference does not work as expected in array

From: Date: Wed, 27 Aug 2014 16:22:13 +0000
Subject: Bug #67916 [Opn->Nab]: Reference does not work as expected in array
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-187300@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=67916&edit=1 ID: 67916 Updated by: requinix@php.net Reported by: qerazor at googlemail dot com Summary: Reference does not work as expected in array -Status: Open +Status: Not a bug Type: Bug Package: Arrays related Operating System: Ubuntu PHP Version: Irrelevant Block user comment: N Private report: N New Comment: 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 After the first foreach $value is still a reference to the last element in $array. When the next foreach begins you reuse $value and that will copy each value you find in the array into that last element. unset($value) after the first foreach. Previous Comments: ------------------------------------------------------------------------ [2014-08-27 14:44:54] qerazor at googlemail dot com Description: ------------ PHP Version 5.5.9-1ubuntu4.1 but am not sure if that maters in this case. one of the foreach takes the value as ref. the other foreach does not. as you can see in the result of the script, the dump of this array after manipulating after the first foreach is correct. but the comparison within the second foreach is wrong. to get that resolved i have to rename one of the $value variables or use the $value variable in the second foreach also as ref. Test script: --------------- $array = array( 'a'=> 'foo', 'b'=> 'foo', 'c'=> 'foo' ); var_dump($array); foreach($array as &$value) { $value = false; } var_dump($array); $array['b'] = true; var_dump($array); foreach($array as $key => $value) { echo $key.' = '.((int)$value).'<br>'; } Expected result: ---------------- array (size=3) 'a' => string 'foo' (length=3) 'b' => string 'foo' (length=3) 'c' => string 'foo' (length=3) array (size=3) 'a' => boolean false 'b' => boolean false 'c' => boolean false array (size=3) 'a' => boolean false 'b' => boolean true 'c' => boolean false a = 0 b = 1 c = 0 Actual result: -------------- array (size=3) 'a' => string 'foo' (length=3) 'b' => string 'foo' (length=3) 'c' => string 'foo' (length=3) array (size=3) 'a' => boolean false 'b' => boolean false 'c' => &boolean false array (size=3) 'a' => boolean false 'b' => boolean true 'c' => &boolean false a = 0 b = 1 c = 1 ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=67916&edit=1

« previous php.bugs (#187300) next »