tags:

views:

157

answers:

6

$clients = $CLIENT->find($options); $client = $clients[0];

EDIT: I Realized i should be clearer. The $CLIENT->find always returns an array of objects, but I want one line of code that turns the array (that will only have 1 object) into just an object.

A: 

Unless ($CLIENT->find($options))[0] works (IIRC I don't think it does in PHP, but don't take my word for it), I don't think you can condense that. I really don't think it's worth worrying about, though - if you need a one-statement expression for it, just write a function.

function fozzyle($options) {
    $clients = $CLIENT->find($options);
    return $clients[0];
}
David Zaslavsky
A: 

$client = $CLIENT->find($options)[0];

doesn't work?

Stefan Thyberg
Not until now, that's the point. This will hopefully be fixed in PHP 6.
Konrad Rudolph
+4  A: 
$client = reset($CLIENT->find($options));

Edit: Here's a less obfuscated one, you should probably use this instead:

list($client) = $CLIENT->find($options);

They aren't identical though; the first one will also work in places where a single scalar is expected (inside a function's parameter list) but the second won't (list() returns void).

Ant P.
This does work, but I'd personally advise against using it. The purpose of the two lines of code in the question is a lot more clear than this condensed version.
Chad Birch
Good point, I'll add a better one as well.
Ant P.
+7  A: 
$client = array_shift($CLIENT->find($options));
sli
thanks, should have seen this coming a mile away
fakingfantastic
A: 

Have you considered method-chaining?

This will allow you to do a lot with only one line of code. Note also that this would be better for larger and more long-term OO solutions. If you just need a quick and dirty solution, perhaps just a custom function that returns the first item in an array.

Help: If somebody can find a better reference for method-chaining, please update this.

Jonathan Sampson
this is an awesome solution, but yes- i was looking for quick and dirty.
fakingfantastic
A: 

$client = array_shift($CLIENT->find($options));

$client will be your object or NULL if find() doesn't return anything.

jab11