I am looking for an elegant way to get the first (and only the first) element of an array that satisfies a given condition.
Simple example:
Input:
[
['value' => 100, 'tag' => 'a'],
['value' => 200, 'tag' => 'b'],
['value' => 300, 'tag' => 'a'],
]
Condition: $element['value'] > 199
Expected output:
['value' => 200, 'tag' => 'b']
I came up with several solutions myself:
Iterate over the array, check for the condition and break when found
Use array_filter to apply condition and take first value of filtered:
array_values(
array_filter(
$input,
function($e){
return $e['value'] >= 200;
}
)
)[0];
Both seems a little cumbersome. Does anyone have a cleaner solution? Am i missing a built-in php function?
Copy the given array to an auxiliary array temp[]. Sort the temp array using a O(nLogn) time sorting algorithm. Scan the input array from left to right. For every element, count its occurrences in temp[] using binary search.
To check if all values in an array are equal: Use the Array. every() method to iterate over the array. Check if each array element is equal to the first one. The every method only returns true if the condition is met for all array elements.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With