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