Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Problems with Variable Variables

need to use dynamic variables for a script



3:51 am on Apr 12, 2008 (gmt 0)

5+ Year Member


Basically I have an array called sidebar_{name-of-the-section-goes-here}, which has a list of Items that need to be added to the sidebar navigation at the left of the page.

So, I created a sidebar that will generate a UL list with all the LI elements according to which section of the site we're in. The URL parameter ?section=home, for instance, would tell the sidebar that it needs to have all items from the $sidebar_home array. Perfect!

The problem I have is that I don't seem to be able to name dynamic variables properly. Here's a simpler version of my code:


$sub_section = $_GET['section'];

for ($i = 0; $i < 5; $i++) {

$sidebar_var_name = "sidebar_" . $sub_section[$i];

echo $$sidebar_var_name . "<br />";



Ok, this is just a simpler version, with no UL or LI tags, but you get the idea.

I don't know what's wrong with my syntax and why this isn't working. Any ideas? Thank you!


3:58 am on Apr 12, 2008 (gmt 0)

5+ Year Member

Also, this is the error I got in my page:

Notice: Undefined variable: sidebar_w in "MY-ROOT-DIRECTORY-GOES-HERE" on line "LINE-NUMBER"

MY-ROOT-DIRECTORY-GOES-HERE and LINE-NUMBER are of course irrelevant here, but you get the idea. The variable is certainly not recognized by the PHP engine.


8:54 am on Apr 12, 2008 (gmt 0)

5+ Year Member

Could you provide some more code, I don't find this very helpful.


4:56 pm on Apr 12, 2008 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member

So what I see here then is that the value of $sub_section[$i] is the string "w" because when you concatenate it to the string "sidebar_" and try to use that variable variable it is saying it is undefined. Another way of writing your code would be ...
$sidebar_var_name = "sidebar_w";

And when you do this ...
echo $$sidebar_var_name . "<br />";

... it is the same as doing this:
echo $sidebar_w . "<br />";

So, is the $sidebar_w variable defined? Obviously not or you would not be getting that error message.


10:28 pm on Apr 13, 2008 (gmt 0)

5+ Year Member

Hello friends,
Turns out I found a solution last night.


// If $my_section = "Home".
$my_section = "home";

for ($i = 0; $i < 10; $i++) {

$my_sidebar_var = "sidebar_" . $my_section;
$sidebar_item = ${$my_sidebar_var}[$i];

echo "<li>" . $sidebar_item . "</li>" . "<br />";


So basically now the loop will call everytime the variable $sidebar_home[$1], which can be $sidebar_home[0], $sidebar_home[1], $sidebar_home[2], $sidebar_home[3] till... $sidebar_home[10]. Thanks for the help guys.


Featured Threads

Hot Threads This Week

Hot Threads This Month