Reputation: 1743
What's the most efficient way to remove items from an array in php where the value is greater than a pre-determined threshold, e.g. given an array
Array
(
[0] => 1.639
[1] => 2.168
[4] => 1.897
[6] => 4.129
)
I would like to remove all the items with a value greater than e.g. 2, preserving key associations, to give
Array
(
[0] => 1.639
[4] => 1.897
)
I know I can do this using a foreach()
loop but it seems that there should be a more elegant way.
Upvotes: 5
Views: 5249
Reputation: 124828
No matter what you use, the array has to be looped through but you can hide it by using array_filter
:
$data = array_filter($data, fn($var) => $var < 2);
Upvotes: 14