Search code examples
phparrayskeyvariable-variables

PHP: Unable to use variable variables for multi-dimensional array access


I'm working on a config tool allowing flexible config for some code to fetch specific array elements (in this example, POST vars). (I am aware this problem could be solved with a recursive call, but ran into a curiosity I don't understand.)

The problem I run into is that variable variables aren't doing what I expect to be able to do.

Does anyone have an explanation for why I can't seem to do this, when logic says I should be able to?

First test

$_POST['a']['array']['key'] = 10;

$thisSearchLocation = '_POST[\'a\'][\'array\'][\'key\']';

echo $$thisSearchLocation;

echo $_POST['a']['array']['key'];

// Expected Output: 1010
// Actual Output: Notice: Undefined variable: _POST['a']['array']['key'] in test.php10

Second test

In this test, it seems I've created a variable using a variable variable that I can only access by re-using the variable variable, and no other way.

$_POST['a']['array']['key'] = 10;

$thisSearchLocation = '_POST[\'a\'][\'array\'][\'key\']';

$$thisSearchLocation = 9;

echo $$thisSearchLocation;

echo $_POST['a']['array']['key'];

// Expected Output: 99
// Actual Output: 910

Solution

  • Variable variables dynamically set variable names. Brackets are not part of the variable name. $_POST is a variable, $_POST['a'] is how you access the a element of the $_POST array.