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.

PHP Numeric Literal Separator

Updated 14th December 2023

First introduced in PHP 7.4, the Numeric Literal Separator in PHP makes large integers within your code easy to read. Naturally, we find it easier to read number which are grouped, for example, 1,650,000. Using the numeric literal separator in PHP Since PHP 7.4, we can now use numbers like this: Adding an underscore between

Create a custom WordPress taxonomy for posts and pages

Updated 16th August 2022

Sometimes when building a website using WordPress, the standard taxonomies Categories and Tags just aren’t enough, and you need to create more. Let’s learn how to create our own custom WordPress taxonomy. WordPress has made creating your own taxonomy easy, and you can even add your custom taxonomies to pages too. To accomplish this we

How to use Microsoft Graph API with Laravel

Updated 1st January 2024

Microsoft Graph is a gateway to data and intelligence within Microsoft 365. Microsoft Graph is great to build apps for organizations and consumers using the vast amount of data stored in Microsoft 365. In this post, we are going to integrate with Microsoft Graph API in Laravel to get all users assigned to your tenant.