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

Josh Sherman
1 min read
Software Development 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.

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Engineering Manager and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles