Variable Variables in PHP

Variables are the cornerstone to all programming. Any programmer will tell you that variables are their best friend, their lover, any number of other weird things… When you need something you simply call $something, and there it is! One of the really cool features of PHP is that in order to call $something, you don’t acutally even need to know $something‘s name, you can use other variables to call it.

This is almost an accompanying reading to the post I did on Dynamic Variables in PHP last week, so please give that a read as well!

Let’s take a look at a really simple example:

In the above example, the part in { … } get’s resolved, and we then call the variable with that name. So ${$Beverly} turns into $Hills and then when we echo that it will of course be Beverly.

Luckily variable variables are useful for more than just making incredibly complicated echo statements. However, now does seem like a good time to mention that variable variables can make code very, very, complex to read. Many sources online recommend not using them just because of this. Please remember this when you do this yourself. You have been warned!

Now let’s take a look at a slightly more complicated example. Say that you have an online store with a search feature where the customer can search by either Company or by Musician.

Traditionally this would be done with something like an if ( … ){ … } else { … } as can be seen in the one below:

However, we can use variable variables to reduce the if ( … ){ … } else { … } section to one simple line of code:

Now let’s say you have the GET variables set to ?fiter=player&index=2. The would output:

Eric Clapton

And that’s pretty much all there is to using variable variables with PHP. Again, I have to remind everyone that this can make your code extremely complex really fast. Please don’t do this and then come back here and tell me that I ruined your site. I personally feel that variable variables are almost more of a theoretical element in PHP that you can think about rather than an actually using in a real world application. However, when dealing with clients sometimes you need software that is extremely flexible to suite their needs. You work hard to prepare the perfectly working application but then the client needs a quick change to account for user input, and this is an extremely easy way to deal with something like that.

As always thank you for reading and please share it around as much as you can! Please feel free to put any questions, suggestions, or ideas in the comments section below. I would really like to know what other kind of tutorials everyone wants me to make, so let me know!

Posted in PHP