Oct
5
2011

Variable variables, how to create dynamic variables in PHPVariable variables, como crear variables dinamicas en 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.

[php]

[/php]

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

[php]
$field = 'quantity';
$$field = 5;
?>
[/php]
OR
[php]
$field = 'quantity';
${$field} = 5;
?>
[/php]

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

[php]
$fname = $_POST['fname']; //Variable for first name
$lname = $_POST['lname']; //Variable for last name
$dob = $_POST['dob']; //Variable for date of birth name
$add1 = $_POST['add1']; //Variable for first address line
$add2 = $_POST['add2']; //Variable for second address line (optional)
$city = $_POST['city']; //Variable for city
$state = $_POST['state']; //Variable for state
$phone = $_POST['phone']; //Variable for phone number
$email = $_POST['email']; //Variable for user email
?>
[/php]

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:

[php]
// All fields that will be processed.
$fields = array('fname','lname','dob','add1',
'add2','city','state','phone','email');
// Have an iteration to create all
// these variables using variable variables.
foreach($fields as $field)
{
${$field} = $_POST[$field];
}
?>
[/php]

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.
En mi post anterior, yo había escrito sobre las variables de PHP y sus diferentes tipos de datos, la forma de dar valores, y también como desplegar al usuario. Si desea leerlo, Aqui está. En este tema, me gustaría que enseñarles lo que son Variable variables en PHP.
Antes de continuar, tenemos que saber que PHP permite un montón de libre albedrío en el área de variables. Otros lenguajes de programación, como PHP, permitirá a los desarrolladores a asignar y cambiar los valores de las variables. La mayoría de estos, sin embargo, no le permiten cambiar el tipo de datos de una variable. Con el fin de hacer eso, usted tendría que hacer algo que se llama “conversión de tipo” o “type casting”. En PHP sin embargo, este no es el caso. Se puede declarar una variable, y una vez se le asigne un valor, entonces, se ocupará un tipo de datos.

Basta, vamos aprender acerca de las Variable variables. Algunas personas me preguntan, ¿por qué escribir sobre esto?. Simple razón. Yo había leído sobre este tema antes, y nunca presté toda mi atención en lo útil que esto podría ser. Eso fue hasta que tuve que tomar un examen de PHP, y vi para mi sorpresa, una pregunta que lee como sigue, ¿Qué es esto, $$var? Realmente no podía recordar el término correcto, pero yo tenía la idea. Después de esta prueba, rápidamente me fui a mi libro de texto, y busqué por todos lados, hasta por fin encontrar, las Variable variables! Nunca más, esta pregunta será un dolor de cabeza para mí. De hecho, he decidido que esta pregunta no sea un dolor para cualquiera de ustedes los lectores. Vamos a echar un vistazo rápido sobre cómo definir estos tipos de variables. Recapitulemos sobre la definición de una variable llamada quantity, con un valor numerico de 5.

[php]

[/php]

Para declarar una ‘Variable variable’, se haría de la siguiente forma:

[php]
$field = 'quantity';
$$field = 5;
?>
[/php]
O
[php]
$field = 'quantity';
${$field} = 5;
?>
[/php]

*Nota rápida: En mi opinión, la segunda manera de hacer esto es mi forma preferida de hacerlo. La razón es simple, se ve un poco más organizada, y cuando se trata de buscar el código y mantenerlo, usted es capaz de detectar con más facilidad, las variable variables, de las variables regulares .

Este ejemplo anterior es exactamente lo mismo que nuestro primer ejemplo. ¿Qué dijo? Sí, es la misma cosa. Así que ¿por qué molestarse haciendo que el camino más largo? No, en realidad es una manera corta, permítanme explicar.

En un formulario web normal, cuando se le pide al usuario algunos datos personales, es probable que pida: nombre, apellido, fecha de nacimiento, dirección, ¿qué ciudad y / o estado en que vive?, tal vez incluso su número de teléfono. No podemos olvidar el correo electrónico, como puede ser que desee ponerse en contacto con este usuario en particular de una manera rápida. Vamos a suponer que ya tenemos un formulario, con todos estos campos, y que va a ser procesada por nuestro proceso de PHP, llamado process.php, y normalmente tendría este método usual:

[php]
$fname = $_POST['fname']; //Variable nombre
$lname = $_POST['lname']; //Variable apellido
$dob = $_POST['dob']; //Variable fecha de nacimiendo
$add1 = $_POST['add1']; //Variable direccion
$add2 = $_POST['add2']; //Variable direccion 2
$city = $_POST['city']; //Variable ciudad
$state = $_POST['state']; //Variable estado
$phone = $_POST['phone']; //Variable numero de telefono
$email = $_POST['email']; //Variable correo electronico
?>
[/php]

No estoy diciendo que esta es una mala idea, pero en el caso que tengamos más de 20 campos que necesitamos para procesar? Nos limitaremos a añadir 20 líneas más de código, para lograr nuestro objetivo. Ahora bien, echemos un vistazo a la magia “Variable variables”. El código anterior se podría reducir un poco a nuestra conveniencia. Echemos un vistazo:

[php]
// Todos los campos a ser procesados
$fields = array('fname','lname','dob','add1',
'add2','city','state','phone','email');
// Tienes una iteración para crear todos los campos
foreach($fields as $field)
{
${$field} = $_POST[$field];
}
?>
[/php]

Como puede ver, todas estas variables que necesitamos, se crean dentro de un bucle “loop”. Si tuviéramos que agregar unos cuantos campos más a nuestra forma, todo lo que tendría que hacer es añadir los nombres de los campos en nuestro array $fields.

Variable variables puede ser divertido de usar, especialmente cuando se tiene una fecha de entrega por venir. Estas realmente pueden ayudarle a acelerar su codificación con facilidad.

Me gustaría saber qué otras maneras puedes utilizar las “Variable variables” para mejorar su código.

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