Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove items from array with value above/below threshold

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.

like image 740
Tomba Avatar asked Dec 12 '22 18:12

Tomba


1 Answers

No matter what you use, the array has to be looped through but you can hide it by using array_filter:

function test($var) { return $var < 2; }
$data = array_filter($data, 'test');
like image 106
Tatu Ulmanen Avatar answered Jan 18 '23 12:01

Tatu Ulmanen