php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #44953 Variable variables dont work in foreach
Submitted: 2008-05-09 09:58 UTC Modified: 2008-05-09 10:27 UTC
From: ies_clan at hotmail dot com Assigned:
Status: Not a bug Package: Variables related
PHP Version: 5.2.6 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: ies_clan at hotmail dot com
New email:
PHP Version: OS:

 

 [2008-05-09 09:58 UTC] ies_clan at hotmail dot com
Description:
------------
If you try to use Variable variables in a foreach, the output of the array is wrong

Reproduce code:
---------------
$array = Array(
	0 => Array('11', '12', '13'), 
	1 => Array('21', '22', '23'), 
	2 => Array('31', '32', '33')
);
$key 	= 'key';
$value 	= 'value';
foreach($array AS ${$key} => ${$value}){
	echo ${$key}." -\n";
}

Expected result:
----------------
1
2

Actual result:
--------------
0
1
2

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-05-09 10:27 UTC] ies_clan at hotmail dot com
oh sry i interchanges the field...

Expected result:
----------------
0
1
2

Actual result:
--------------
1
2
 [2008-05-09 10:27 UTC] colder@php.net
Sorry, but your problem does not imply a bug in PHP itself.  For a
list of more appropriate places to ask for help using PHP, please
visit http://www.php.net/support.php as this bug system is not the
appropriate forum for asking support questions.  Due to the volume
of reports we can not explain in detail here why your report is not
a bug.  The support channels will be able to provide an explanation
for you.

Thank you for your interest in PHP.

This is expected:
The evaluation of ${$key} in your foreach is done at each loop.
So you're overwriting $key with $$key as $key is initially "key". 

$key 	= 'otherkey';
$value 	= 'othervalue';
foreach($array AS ${$key} => ${$value}){
	echo ${$key}." -\n"; // echo $otherkey." -\n"
}

will work just fine.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Dec 27 02:01:29 2024 UTC