views:

43

answers:

2

Some searching through Google (and my own experience) shows that in PHP you can't grab an array element when it's been returned from a function call on the same line. For example, you can't do:

echo getArray()[0];

However, I've come across a neat little trick:

echo ${!${false}=getArray()}[0];

It actually works. Problem is, I don't know why it works. If someone could explain, that would be great.

Thanks.

+3  A: 

it works because your using the braces to turn the value into a varialbe, heres an example.

$hello = 'test';
echo ${"hello"};

Why is this needed, this is needed encase you want to turn a string or returned value into a variable, example

${$_GET['var']} = true;

This is bad practise and should never be used IMO.

you should use Objects if you wish to directly run off functions, example

function test()
{
   $object = new stdClass();
   $object->name = 'Robert';

   return $object;
}
echo test()->name;
RobertPitt
+2  A: 
echo ${!${false}=getArray()}[0];

This is how it works, step by step

${false}=getArray()

assigns the result of getArray to a variable with an empty name ('' or null would work instead of false)

!${false}=getArray()

negates the above value, turning it to boolean false

 ${!${false}=getArray()}

converts the previous (false) value to an (empty) string and uses this string as a variable name. That is, this is the variable from the step 1, equal to the result of getArray.

${!${false}=getArray()}[0];

takes index of that "empty" variable and returns an array element.

Some more variations of the same idea

echo ${1|${1}=getArray()}[1];
echo ${''.$Array=getArray()}[1];

function p(&$a, $b) { $a = $b; return '_'; }
echo ${p($_, getArray())}[1];

As to why getArray()[0] doesn't work, this is because php team has no clue how to get it to work.

stereofrog
Perfect, thanks.
Daniel
great examples, very informative +1
RobertPitt