Tomba
Tomba

Reputation: 1743

Remove elements from a flat array if value is greater than a given number

  1. List item

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

Answers (1)

Tatu Ulmanen
Tatu Ulmanen

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

Related Questions