ifaour
ifaour

Reputation: 38135

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

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.

Upvotes: 2

Views: 4505

Answers (4)

flu
flu

Reputation: 14683

In PHP 5.4 this becomes an easy one-liner

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.

$firstElement = getArray()[0];

where

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

Taken from a slightly modified version of Example #7 from the PHP manual pages (Arrays).

Upvotes: 2

Engin
Engin

Reputation: 166

For the first one, you can do this trick... for other indices, it gets uglier.

list($algo) = explode(':', $password);

I was looking for a more elegant answer but here we are :)

Upvotes: 0

Victor Nicollet
Victor Nicollet

Reputation: 24577

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

Upvotes: 5

Pekka
Pekka

Reputation: 449515

Nope, as far as I know, there is no way to do this in PHP.

What you could do is return an object of a class that has a method getLine(). With that, you could do

$item = $this->prepare_items(array($item))->getLine(0);

you could - I'm not saying it's necessarily always a good idea, but it's becoming more and more popular, probably influenced by jQuery's elegance - also store the results of get_item in the object, and have it return $this to allow for method chaining like so:

$item = $this->get_item($id)->prepare_items()->getLine(0);

Upvotes: 2

Related Questions