Search code examples
phparraysdictionaryarray-filter

How to get array key with less than values


I have 2 arrays:

$arr_1=array(200, 300, 200, 200);

$arr_2=array(
    1 => array(70, 90, 70, 20),
    2 => array(115, 150, 115, 35),
    3 => array(205, 250, 195, 55),
    4 => array(325, 420, 325, 95),
    5 => array(545, 700, 545, 155)
);

Now I need some way to get array keys for arrays in $arr_1 where all their values are less than all values from $arr_2.

In the above example it must return key 1 AND key 2 from $arr_2 without using a foreach loop.


Solution

  • You can use array_filter to filter the elements (it preserves keys) and then pass the result to array_keys to receive an array of keys.

    Also, your condition can be spelled this way: "return subarrays from $arr_2 where highest value is smaller than smallest value of $arr_1."

    $arr_1=array(200, 300, 200, 200);
    
    $arr_2=array(
        1 => array(70, 90, 70, 20),
        2 => array(115, 150, 115, 35),
        3 => array(205, 250, 195, 55),
        4 => array(325, 420, 325, 95),
        5 => array(545, 700, 545, 155)
    );
    
    $filtered = array_filter($arr_2, function($value) use ($arr_1) {
        return max($value) < min($arr_1);
    });
    $keys = array_keys($filtered);
    
    var_dump($keys);