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.