Remove array elements that are less than X

Posted by GGio on Stack Overflow See other posts from Stack Overflow or by GGio
Published on 2014-06-12T20:53:32Z Indexed on 2014/06/12 21:25 UTC
Read the original article Hit count: 145

Filed under:
|

I have arrays:

$arr1 = array(5, 3, 9, 11, 6, 15);
$arr2 = array(11, 20, 1, 3, 8);

Now I need to loop through $arr1 and find the largest number that is less than X:

foreach($arr1 as $x) {
   //need element that is MAX in $arr2 but is less than $x
}

so for example for the first run when $x = 5, maximum in $arr2 is 3 that is less than 5.

Is it possible to do this without having nested loop? I do not want to loop through $arr2. I tried using array_filter but didnt really work. Maybe I used it wrong.

This is what I tried with array_filter:

$results = array();
foreach($arr1 as $x) {
   $max = max(array_filter($arr2, function ($x) { return $x < $y; }));

   $results[$x] = $max;
}

The result should be this:

5  => 3, 
3  => 1, 
9  => 8, 
11 => 8, 
6  => 3, 
15 => 11

© Stack Overflow or respective owner

Related posts about php

Related posts about arrays