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.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

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


If you found this article helpful, please consider buying me a coffee.