First element of array by condition
The shortest I could find is using current
:
current(array_filter($input, function($e) {...}));
current
essentially gets the first element, or returns false
if its empty.
If the code is being repeated often, it is probably best to extract it to its own function.
There's no need to use all above mentioned functions like array_filter
. Because array_filter
filters array. And filtering is not the same as find first value. So, just do this:
foreach ($array as $key => $value) {
if (meetsCondition($value)) {
$result = $value;
break;
// or: return $value; if in function
}
}
array_filter
will filter whole array. So if your required value is first, and array has 100 or more elements, array_filter
will still check all these elements. So, do you really need 100 iterations instead of 1? The asnwer is clear - no.