zerkms
zerkms

Reputation: 254916

Notice and warnings-free way to retrieve the first element of array

Let's suppose we have 2 functions. First returns an array with 0..N elements and the second need to return only the first element or NULL if there are no any.

Assuming we have such a code:

/**
 * return stdClass[]
 */
function foo()
{
    return ...;
}

/**
 * return stdClass|null
 */
function bar()
{
    $arr = foo();

    if ($arr) {
        return $arr[0];
    }
}

As you can see the implementation of bar() is boring.

If I used .NET then I would use arr.FirstOrDefault() method and it would suit the task perfectly.

What would be the most elegant way of doing that in php?

PS: the answers that generate any kind of warnings or notices are not accepted. As well as the ones that use @ to suppress errors

Upvotes: 0

Views: 64

Answers (2)

sectus
sectus

Reputation: 15464

$return = ($arr = foo()) ? reset($arr) : null;

Why you cannont use current

function foo()
    {
    $array = array(1,2,3);
    next($array);
    return $array;
    }

echo current(foo()); // 2

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173552

You could use current() for that, assuming foo() doesn't change the array pointer (using next() for instance), coupled with a ternary operator:

return current(foo()) ?: null;

This will obviously have odd results if you have scalars in your array that evaluate to false, but will work fine if all elements are objects.

Alternatively, to guard against modifications done by foo() you could use reset() as well:

return reset((foo())) ?: null;

Warning

Note the extra parentheses in the above code, they're not superfluous and is based on a peculiarity in the language; this behaviour may change in the future, so you shouldn't rely on it. It would be safer to introduce a temporary variable.

Upvotes: 5

Related Questions