1

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!

1
  • Why are you using variable variables instead of an associative array? Commented Jan 6, 2014 at 22:48

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.