Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define array index after function call

In other languages such as C# and JavaScript, I am able to access the index of an array with a function call such as

getMyArray()[0] 

This would allow me to access the first index of the result instead of passing back the entire array and then setting the result.

However this shortcut does not work with PHP. Is there a way to get this shortcut?

like image 995
John Avatar asked May 26 '12 16:05

John


2 Answers

You need to be running PHP 5.4 in order to use array de-referencing.

like image 87
John Conde Avatar answered Sep 23 '22 19:09

John Conde


// PHP 5.4
$item = getMyArray()[0];

// Older than 5.4: (not recommended)
list($a)   = getMyArray();  // getMyArray()[0]
list(, $b) = getMyArray();  // getMyArray()[1]
like image 33
flowfree Avatar answered Sep 19 '22 19:09

flowfree