Question

Below is the code sample:

$test = array(
    1 => 'one',
    2 => 'two',
    3 => 'three'
);

$arrayName = 'test';

error_log(print_r($$arrayName, 1));
error_log($$arrayName[1]);

The output:

 Array
(
    [1] => one
    [2] => two
    [3] => three
)
PHP Notice:  Undefined variable: e in /Applications/MAMP/htdocs/_base/test.php on line 12

I was hoping that the second line would output 'one' and obviously it didn't work. It seems that the brackets has a higher parsing priority so $arrayName is treated as array here.

I tried using curly brackets to wrap the $$arrayName first, somehow it lead to a PHP Parse error. Since eventually I will need to use unset to remove the selected element, therefore using an temporary variable to store the array is not ideal. Wonder if there is any way that I can achieve this within one line. Any insight is appreciated!

Was it helpful?

Solution

Use:

error_log(${$arrayName}[1]);

See the PHP documentation of Variable Variables. It explains that you have to use braces to resolve the ambiguity. It needs to know whether you want to use $$arrayName as the variable or $arrayName[1] as the variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top