Oct
5
2011

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:

OR

*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.



About the Author: Jorge Torres

MS. Computer Science Codeigniter Web Developer

11 Comments+ Add Comment

  • Jorge, I like the post very much! Especially the last example, I can see how this approach would be very helpful for security.

    Keep them coming!

  • 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.

  • [...] from post that do not require you as a developer to write so many lines of code. See this post on Variable variables to get an idea of how can you optimize this [...]

  • 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.

  • I like the post very mush especially last exmple is super ya…

  • 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.

  • 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.

  • 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…

  • Hi i have used it in codeigniter just used not more that it but today i have realize how powerfull this thing it is

  • to extract the values ​​of the array $ _POST I use:
    extract ($ _POST);

  • 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.

Leave a comment