Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
    
Why are you using variable variables instead of an associative array? –  Barmar Jan 6 '14 at 22:48
1  
${$arrayName}[1]; –  DavidLin Jan 6 '14 at 22:51

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer
    
+1 for the explanation –  kapa Jan 6 '14 at 22:53
    
Thanks, should have read the manual more carefully –  aarryy Jan 7 '14 at 0:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.