1

I have a function returning an array: function foo(){ return array('foo'=>1,'bar'=>2); }

Can I access an element of the return array without assigning it to a temporary variable first (e.g. foo()['bar'])?

The following example returning an object works like a charm:

function foo(){ return (object) array('foo'=>1,'bar'=>2); }
echo foo()->bar;
tstenner
  • 10,080
  • 10
  • 57
  • 92

1 Answers1

4

No, unfortunately PHP's grammar doesn't allow this. There is no good reason for this btw (there are a few discussions about it on PHP mailinglists).

If you really want it, you could consider switching to Python - it not only supports inline access to returned arrays but also many other nice things. ;)

Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • @prodigitalson: I have PHP 5.3.3-7 and it doesn't work either. – emco Apr 03 '11 at 08:06
  • If I had a choice, I'd use C++, Scala, Python, JavaScript (?) etc., they not only support inline acces to returned arrays but also many other nice things... – tstenner Apr 03 '11 at 08:14