If I have a function that returns an array, how can I access a key from it directly from the function call?
Example:
function foo() {
return array('a' => 1);
}
foo()['a']; //no good
You can't do it directly like that in versions < 5.4. You need to store the return value of foo() somewhere:
function foo() {
return array('a' => 1);
}
$bar = foo();
echo $bar['a'];
In PHP 5.4 and up, your code will work. Demo.
You have to assign the function to a variable first - like this:
$bar = foo();
$bar['a'];
You have to actually call a function to get a return value - in this case you are trying to get an array value from something which is not an array.
Note, this is true only for versions of PHP before 5.4.
foo()[1]is valid syntax. ide's such as dreamweaver won't recognize it as such though and will throw big red lines. but it definitely is possible