Web Statistics

Variable Variables

A variable of a variable is indeed a new variable.

Another way to create a variable

We've already covered how to establish variables in your code. Wait for it... wait for it... BUT! Did you know there is another way to define variables that can be convenient in certain situations. Let me warn you that doing this in all situations to define a variable, others (including myself) will look at your code with a clear look of "what the hell..."

Let's look at a possibe situation to utilize this and how it works. Take a simple variable that defines a multidimensional array value:

<?php
$foo = array(
    'apples'=>'red', // because some apples are red
    'bananas'=>'yellow',
    'oranges'=>'orange' // yes, oranges are indeed orange
);
?>

What we have done so far is to define the variable $foo with a multidimensional array value (we will get into arrays later). Now let's just say that your code needs the array converted into a variable for each array key (apples, bananas, oranges) with it corresponding value (red, yellow, orange). However, this array value comes from a source outside your control, so you can not edit the source to produce the desired output there. What we need to do then is break the array up into it's pieces and define new variables accordingly. Here's how we go about this.

<?php
$foo = array(
    'apples'=>'red', // because some apples are red
    'bananas'=>'yellow',
    'oranges'=>'orange' // yes, oranges are indeed orange
);

foreach ($foo as $fruit => $color) {
    $$fruit = $color;
}
?>

We haven't gone over the foreach control structure yet, but we will. So let's take a look at this.

foreach ($foo as $fruit => $color) {...}

In this part we are applying a loop that will iterate through the array $foo. The key is in the part where we seperate the array key from the value ($fruit => $color). By doing this we are essentially creating a variable for the key and one for the value. It makes the two easy to work with. Now for the fun part. Did you notice the two dollar signs?

$$fruit =

No that's not a typo. We are taking the value of $fruit, let's say apple, and creating a new variable called $apple defining it with the value of $color. Which is red.

Out in the "real world" you might also see something like:

<?php
foreach ($foo as $fruit => $color) {
    ${$fruit} = $color;
}
?>

Don't let the curly braces freak you out. It's doing the same thing we are talking about. There's a lot more that can be written about this concept as I see it almost daily. Play with this a bit and become familiar with it. The concept of variable variables can come in handy from time-to-time.

Up Next

Ah variables! Where did you go?