Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove array elements that are less than X

Tags:

arrays

php

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
like image 415
GGio Avatar asked Jun 12 '14 20:06

GGio


1 Answers

The problem is with the use of the lambda - PHP does not automatically capture variables in the enclosing scope. (The official Anonymous Functions is a bit sparse on the topic, so see In PHP 5.3.0, what is the function "use" identifier? as well.)

Compare the original, which returns an empty array as it is effectively $x < undefined

$arr2 = array(11, 20, 1, 3, 8);
$y = 5;
var_dump(array_filter($arr2, function ($x) { return $x < $y; }));

with the following that employs the use syntax to bind the variable in the function

$arr2 = array(11, 20, 1, 3, 8);
$y = 5;
var_dump(array_filter($arr2, function ($x) use ($y) { return $x < $y; }));

(Also, in the original code there was no $y variable at all, whoops!)

like image 165
user2864740 Avatar answered Sep 19 '22 15:09

user2864740