-1

Is there a way to access a specific element of an array that's returned from a function in PHP right from the function call? Let's say I have a function called getMostRecentPost() and it returns an array. I want to be able to do something like this:

echo getMostRecentPost()['title'];

That doesn't work. Other languages seem to allow this kind of syntax though. Right now my solution is to do this:

$mostRecentPost = getMostRecentPost();
echo $mostRecentPost['title'];

Are there any shortcuts that will allow me to cut out declaring a variable? Do I have my syntax wrong?

Aaron
  • 10,386
  • 13
  • 37
  • 53
  • possible duplicate of [PHP: Can I reference a single member of an array that is returned by a function?](http://stackoverflow.com/questions/68711/php-can-i-reference-a-single-member-of-an-array-that-is-returned-by-a-function) – Esailija May 30 '12 at 19:11
  • http://stackoverflow.com/questions/971489/php-how-to-get-object-from-array-when-array-is-returned-by-a-function http://stackoverflow.com/questions/1664362/access-an-array-returned-by-a-function – Esailija May 30 '12 at 19:12
  • Whoops, guess I shouldn't have opened this question so quickly. My fault – Aaron May 30 '12 at 19:13

3 Answers3

1

That's possible with PHP 5.4, quoting:

As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable.

Example from php.net:

function getArray() {
    return array(1, 2, 3);
}

// on PHP 5.4
$secondElement = getArray()[1];

More Info:

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
0

No, but you can do it with objects. If getMostRecentPost() returned an object you could go

echo getMostRecentPost()->title;
None
  • 5,491
  • 1
  • 40
  • 51
0

It's a new feature in php 5.4

function arr(){return [5];}
echo arr()[0];

http://codepad.viper-7.com/z6xPrL

goat
  • 31,486
  • 7
  • 73
  • 96