PHP Variable Variables

By Dillon Smart · · · 0 Comments

Understanding PHP Variable Variables

In PHP, it is sometimes necessary to have variables that have variable names. Traditionally, a variable is given a name and a value is given to the variable like so:

$foo = 'bar';

A Variable Variable, or Double Dollar Variable, gets its name from the value of another variable like so:

$foo = 'bar';

$$foo = 'Foo Bar';

echo $bar;

// output 'Foo Bar'

In the example above, the Variable Variable has been given the name of foo. The use of the double dollar operator gives the variable the name which is the value of foo. In this case, the value of foo is bar.

Limitations of using Variable Variables in PHP

Although PHP has the Variable Variable operator built-in, there are reasons to use more traditional ways of assigning values. The biggest drawback of Variable Variables is speed.

PHP Variable with an assigned value

PHP variable speed

PHP Array with one key-value pair

PHP Array Key Value Pair Speed

PHP Variable Variables

PHP Variable Variable Speed Difference

 

As you can see, there is a significant speed difference when using Variable Variables. Wherever you have data that you could access using a Variable Variable, an array should be used for the most efficient code.

Learn more about Variable Variables in the official documentation.

Check these PHP Statistics!

PHP

0 Comment

Was this helpful? Leave a comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.

How to check Composer version – Install and use Composer for PHP

Updated 11th January 2024

Composer is a dependency manager for PHP. First released in 2012, Composer, and its adoption by popular frameworks such as Laravel has single-handedly driven the rise in PHP adoption in recent years. In this post, I will show you how to install and use Composer. How to install Composer To get started, download Composer from

How to setup a remote MySQL database connection in PHPStorm

Updated 1st October 2023

PHPStorm is packed full of features designed to make the development process for PHP developers efficient and streamlined. Although Jetbrains have a standalone product for interacting with databases, named DataGrip, PHPStrom ships with the Database Tools and SQL plugin. This tools is powerful, integrated directly within the IDE, and provides a convinient way to intract

Laravel php artisan make:auth command not defined

Updated 11th August 2022

Laravel 6.0 LTS came with a lot of changes to the framework, apart from moving the the new Semantic Versioning, Laravels famous php artisan make:auth command was dropped. php artisan make:auth Before the Laravel make:auth command would create all the Migrations, Models, Controllers and Routes needed to easily setup an authenticatable application in seconds. However,