homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

Change / get variable name dynamically
using FOR loop to get variable - help with basic syntax please

 4:56 am on Sep 14, 2011 (gmt 0)


a real basic one that has me stumped - I have a FOR loop, and I want to display the contents of a set of variables. E.g.:

$var1 = "Hello";
$var2 = "How are you?";
$var3 = "Merry Christmas";
$var4 = "Nice Day";

echo ["var".$i];

I've been hunting around for a while, the only thing I could find was some reference to using square brackets. Only I can't get it to work, could someone point me in the right direction?

Much appreciated as always.




 6:29 am on Sep 14, 2011 (gmt 0)

Would you be better off using an array?

Then you'd use $var[0] to $var[3] instead and in the loop you'd use $var[$i].


 6:42 am on Sep 14, 2011 (gmt 0)

I agree, an array is the natural choice for this sort of thing, but to answer your question: If the vars are in the global scope they are already in an array (the $GLOBALS array), so yeah the square bracket notation will work here:
$var1 = "Hello";
$var2 = "How are you?";
$var3 = "Merry Christmas";
$var4 = "Nice Day";

echo $GLOBALS['var'.$i].'<br>';

Now, if the vars would happen to be within a function, you could get them from an array via get_defined_vars()which gives you the variables contained in the current scope (function scope as opposed to global scope):
function privateVars() {
$v1 = 'Nice day';
$v2 = ', is it';
$v3 = ' not?';
$allVars = get_defined_vars();
for ($i = 1; $i < 4; $i++) {
echo $allVars['v'.$i];



 7:49 am on Sep 14, 2011 (gmt 0)

Or, variable variables [uk3.php.net].

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved