joshtronic

in Software Development #PHP

Working with Dynamic variable names a/k/a Variable variables in PHP

Variable variables are one of my favorite things about PHP. PHP allows you to use a variable to reference another variable. This comes in exceptionally handy when you need to create variable names dynamically:

$variable = 'This is my variable';
$var      = 'variable';

echo $$var;

Let's say you have you have a variable that uses another variable as part of the name:

$array         = range(1, 100);
$format_json   = json_encode($array);
$format_serial = serialize($array);

$format = 'json'; $variable = 'format_' . $format;

echo $$variable;

Granted this is a very simple example to demonstrate the functionality. Real world usage could end up being more complex and really show off the power of variable variables.