Search code examples
phpfunction-calldynamic-variables

Explain this convoluted example of nested dynamic variable assignment to immediately access data from a function call


function ReturnArray() {
    return array('a' => 'f', 'b' => 'g', 'c' => 'h', 'd' => 'i', 'e' => 'j');
}

echo ${!${!1}=ReturnArray()}['a']; // 'f'

Please explain what's the logic and step of compute with those ${!1} in the above resolution that works well.


Solution

  • Let's start with some basics. In PHP, something like hello will evaluate to the string "hello". To reference a variable, you can use this syntax: ${expr}. There's also a shorthand for this, $foo, which will roughly evaluate to this: ${"foo"}.

    Also, you probably know that you can assign multiple variables at once: $a=$b=$c='hello';, for example. This will assign $a, $b, and $c to 'hello'. This is actually represented as $a=($b=($c='hello')));. $foo=value is an expression which, after $foo is set, will evaluate to value.

    Your code statement looks like this:

    echo ${!${!1}=ReturnArray()}['a'];
    

    The first thing it does, obviously, is call ReturnArray. It then evaluates !1, which evaluates to false. The ${!1} therefore makes a variable with the name false, though not a string(?!). After that, it applies a not operation to the array. All non-empty arrays are truthy, so the not operation changes it to false. It then uses that ${} syntax again to retrieve the variable named false. It then uses an array access to retrieve the value in the array for key 'a'.

    I hope that made sense.