Home » Programming » PHP » Safely Using PHP Variable Variables with Arrays [Examples]

Safely Using PHP Variable Variables with Arrays [Examples]

PHP variable variables are a powerful way to add flexibility to your code. This article explains the pitfalls and solutions to using them with arrays.

Variable variables are a great way to simplify your code and make it more readable. However, when using them with arrays, you need to be careful.

PHP Arrays and Variable Variables

To use variable variables with PHP arrays, extra considerations need to be taken to resolve potential ambiguities in your code.

Consider the following PHP code:

$myArray = ["dog", "bird", "bear"];
$$myArray[1] = "fish";

To what exactly is the array key referring?

Is $myArray[1] being used as the variable variable name, creating a new variable with the name $bird and the value fish, or is $$myArray the variable, and we are trying to access index [1] from it?

This ambiguity causes problems, as PHP cannot know which you mean. Curly braces can be used to clarify this – the above alternatives should be expressed as ${$myArray[1]} for the first scenario and ${$myArray}[1] for the second.

Curly braces delimit where the individual components of each statement begin and end, much like parenthesis in mathematical equations.

Photo of author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment