How to return an array and get the first element of it in a single line in PHP?

advertisements

this question is just for fun and maybe learning a PHP shorthand trick (if exists) Let's assume that I have this code:

$item = $this->get_item($id);
$item = $this->prepare_items(array($item));
$item = $item[0];

By default, *prepare_items* function takes an array of items and return them with some modifications so if I want to call it on one item only I should push it into an array like above, but then I have to pull out the item from the array I created.

So is there a shorthand way to do this, like:

$item = $this->_prepare_items_output(array($item))[0];
// OR
$item = ($item = $this->_prepare_items_output(array($item)))[0];

Also if you have a link for a set of tips and tricks for PHP that would be great.


You can use reset($array) to reset the internal array position and return the value of the first element.