0

I created code below, but works only for PHP 7+ version.

What I need to change here to make $$variablename[$key] work on 5.6 version?

Online PHP test

$g_module_id_bar_1['id'] = 5;

$i = 1;

$variablename = 'g_module_id_bar_'.$i;
$key = 'id';

echo $$variablename[$key];  // doesn't work

Result should be: 5

Stphane
  • 3,368
  • 5
  • 32
  • 47
  • 2
    `echo ${$variablename}[$key];` Someone else can turn that into a proper answer with reference links to why curly braces work in this situation ;) – IncredibleHat Jul 30 '18 at 15:04
  • Related: https://stackoverflow.com/questions/34092299/variable-variables-handling-order-changes-in-php-7 – Don't Panic Jul 30 '18 at 15:52

1 Answers1

3

In PHP 5, you should write

echo ${$variablename}[$key];

The reason why the code in your question works in PHP 7 is that PHP 7 introduced changes in how it handles indirect variables:

Indirect access to variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the previous mix of special cases. The table below shows how the order of evaluation has changed.

More specifically, the following expression: $$foo['bar']['baz']

Was interpreted in PHP 5 as: ${$foo['bar']['baz']}

And in PHP 7: ($$foo)['bar']['baz']

Source: http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.variable-handling.indirect

Catalyst
  • 1,018
  • 2
  • 12
  • 19