1

Why does this code fail

function f(){
    return array('k'=>'abc');
}
print_r(f()['k']);

and this code work?

function f(){
    return array('k'=>'abc');
}
$a = f();
print_r($a['k']);

The only difference is the assignment of f's result to $a before trying to access elements of the array. How can I reference the result of f directly without the additional assignment?

Trindaz
  • 17,029
  • 21
  • 82
  • 111
  • I would hit my head, but that would make me lose more braincells than I already have reading about this issue .. – user2246674 Jun 18 '13 at 06:46
  • 2
    @user Hooray for language wars on SO! – deceze Jun 18 '13 at 06:48
  • @deceze Oh, I toned it down. But it's not a [language] war without an opponent .. I've wasted enough time learning about another "interesting" design decision; although I guess I *did* learn something new :D – user2246674 Jun 18 '13 at 06:49

1 Answers1

6

This is only available in PHP 5.4. It is known as array dereferencing. Prior to 5.4 you have to store the return value and then access the array elements.

Docs

PHP 5.4.0 offers a wide range of new features:

  • Function array dereferencing has been added, e.g. foo()[0].

If you try this on any version below 5.4, you will get this error:

Parse error: syntax error, unexpected '[' on line ...

Community
  • 1
  • 1
MrCode
  • 63,975
  • 10
  • 90
  • 112