October 5, 2011 var_var

Variable variables, how to create dynamic variables in PHP

Variable variables

On my previous post, I had written about PHP variables and their different data types, how to give them values, and also display them to the user. If you would like to read the post, Read it here. On this topic, I would like to teach you what Variable variables are in PHP.
Before proceeding, we need to know that PHP allows a lot of free will in the area of variables. Other programming languages, just like PHP, allow developers to assign and change variable values. Most of these though, do not allow you to change the data type of a variable. In order to do that, you would need to do something called ‘type casting’. In PHP however, this is not the case. You can declare a variable, and once the value is assigned, then will it take a data type.

Enough, on to the variable variables. Some people ask me, why do I write about this. It is all simple. I had read about this subject before, and never put my full attention onto how useful this could be. That was until I had to take a PHP quiz, and saw to my surpise, What is this, $$var? I couldn’t really remember the correct term, but I had the idea. After this quiz, I rapidly went to my old text book, and was looking all over for it, and there it was, Variable variables! Never again, will this question be a pain for me. In fact, I have decided for this question not to be a pain for any of you readers out there. Let’s take a quick look on how to define these types of variables. Let’s recap on defining a variable named quantity, and have the value of 5.

If we were to name a variable variable, we would do the following approach:


*Quick note: On my opinion, the second way of doing this is my way of doing it. The reason is simple, it looks a bit more organized, and when it comes to searching old code, you are able to spot these, separating them from regular variables a lot faster than the first.

This previous example is exactly the same as our first example. Say what? Yes it’s the same thing. So why bother doing it the long way? No, it’s actually a short way, let me explain.

In a normal web form, when asking the user for some personal information, we would probably ask for: name, last name, date of birth, address, what city and/or state are they from, maybe even their phone number. We cannot forget the email, as we might want to get in touch with this particular user in a fast manner. Let’s pretend we already have a form, with all these fields, and it is going to be processed by our php file process.php. We would normally have this regular approach:

I am not saying this is a bad idea, but what if we have 20 more fields we need to process? We will just add the 20 more lines of code, achieving our goal. Now, let’s look at variable variables magic. The above code could be reduced slightly to our convenience. Let’s take a look:

As you can see, all these variables that we need, are created within a loop. If we were to add some more fields to our form, all we would have to do is add those field names into our array $fields.

Variable variables can be fun to use, especially when you have a deadline coming up. These can really help you speed up your coding as-well. I hope this post helps at least one person, that would make me happy.

I would like to know what other ways you guys use variable variables to enhance your code.

15 thoughts on “Variable variables, how to create dynamic variables in PHP

  1. Thanks Arlo, I’m glad you noticed, as I did write it with that intention.

    I was asked if it can be done directly using just:

    foreach($_POST as $key => $value)

    and yes, it can be done, but unless it has a proper filtering, then the website could be in danger. For me, the last example is my best approach on this. That way, if malicious injection comes our way, it will be a bit harder for them to infiltrate.

  2. Very nice article indeed Jorge. I have read a lot about this variable variable but never did it come to me of using it this way. The last example is really a great one.

    And yes, looping through just $_POST can be a lot more harmful then one can imagine.

    Hope to see many more of such articles.

  3. I like the examples, this is not a topic I see covered very often, but I would suggest a caveat or two to the bottom example where you use this method to convert $_POST elements to variables. First, there is already a language construct to do this, called extract(), which converts array members to variables. Second, there is a large security issue when doing this with any type of user-supplied data. A malicious user could feed extra post fields to your script to try to cause this technique to overwrite trusted variables in your script with unsafe contents.

  4. Thanks William for your feedback, and yes, I have to agree with you on malicious users intent. That is why I give the last example. If I were to change the variable name to something like: $allowed_fields or something like that, then you would see how it would help security a bit when using predefined fields. Also, using extract alone could fall into malicious users and be dangerous as well. It would need for some security measures taken by the coder, in order to do this a good way.

  5. Because of this I love programming!

    tnx this was great note… I haven’t any idea about this $$variable thing…
    i’m young in php… but this is cool…

  6. Hola jorge, muy bueno tu post, pero me preguntaba, como manipularias la info si los campos que estas creando son dinamicos, es decir, por ejemplo una lista de compras de productos diferentes, en la cual agregues campos solo cuando los necesites.

  7. Que absurdez publicaste..
    Con un simple:

    foreach($_POST as $field) {${$field} = $field;}

    lo haces TODO y te ahorras el array y el resto de basura, ya que enseñas hazlo bien… majete.

    1. Mira tonto, gracias por ser tan bestia y escribir a lo loco. La razon por la cual no se debe utilizar $_POST as $field es simple, pero creo que en tu cabeza no cabe tanta inteligencia. Es algo simple, y por seguridad, defines cuales son las variables que quieres extraer. Esto es, si acaso viene alguien con mala intencion a querer añadir información que usted no desee.

      Vez que simple…

      Gracias por el comentario caballero.

  8. no, gracias a ti por insultar…
    dejas muy claro donde entra esta gente y aun no publicando este mensaje se vera.

    sobre tu duda de seguridad si al menos supieras un poco de PHP podrias resolverla en una simple linea, aprende y luego escribe que en internet hay mucha mierda ya publicada… por favor, aprende…
    Tu educacion es secundaria, siempre se puede aprender de un mal educado pero aprende y luego enseña.

    un saludo desde ESPAÑA

  9. Lo extraordinario del ejemplo, para mi, es que se amolda a mi necesidad, y eso lo hace invaluable, en internet hay mucho código pero no es muy claro a veces como resuelve tu necesidad. Dicho esto de tu ultimo ejemplo como saco el valor de la variable variable. Es decir para ponerlo en un while y que me imprima como si hubiera hecho un

    echo “<td>$fname</td><td>$lname</td>…”;

    Muchas gracias por todo.

Leave a Reply

Your email address will not be published. Required fields are marked *

The qTranslate Editor has disabled itself because it hasn't been tested with your Wordpress version yet. This is done to prevent Wordpress from malfunctioning. You can reenable it by clicking here (may cause data loss! Use at own risk!). To remove this message permanently, please update qTranslate to the corresponding version.