Skip to content
Advertisement

Group Array By Range Value

I have this array [1,1,2,2,2,3,4,4,5,6,6,6,7], may I group the array according to the range value, so get the final result:

'1-3' = [1,1,2,2,2,3]; // Count is 6 '4-5' = [4,4,5]; // Count is 3 '6-7' = [6,6,6,7]; // Count is 4

Advertisement

Answer

What you need I believe is:

function array_get_range($array, $min, $max) {
    return array_filter($array, function($element) use ($min, $max) {
       return $element >= $min && $element <= $max; 
    });
}

$array = [1,1,2,2,2,3,4,4,5,6,6,6,7];

$range13 = array_get_range($array, 1, 3); // [1, 1, 2, 2, 2, 3]
$range45 = array_get_range($array, 4, 5); // [4, 4, 5]
$range67 = array_get_range($array, 6, 7); // [6, 6, 6, 7]
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement