Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain this fragment of PHP for me: returning array and immediately reference an index

Tags:

php

<?php
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.

like image 832
Pentium10 Avatar asked Jun 18 '11 20:06

Pentium10


3 Answers

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.

like image 90
icktoofay Avatar answered Nov 02 '22 11:11

icktoofay


  1. !1 = false
  2. ${!1} = NULL
  3. ${!1} = ReturnArray() = array('a' => 'f', 'b' => 'g', 'c' => 'h', 'd' => 'i', 'e' => 'j')
  4. so now $NULL contains array
    and again we see construction ${!(condition) which means $NULL (see first and second points), so we can convert it to:
  5. $NULL['a'] (and $NULL contains array)

You can easily check this:
print_r(${NULL}); - you'll see array ;)

like image 45
OZ_ Avatar answered Nov 02 '22 10:11

OZ_


${!1} evaluates to ${false}
!${false = ReturnArray()} evaluates to $true = array('a' => 'f', /* etc */).
echo $true['a'] produces 'f' as 'f' corresponds to index 'a'

I'm curious now, what is this from?

like image 31
Dan Lugg Avatar answered Nov 02 '22 09:11

Dan Lugg