php – Group Array By Range Value-ThrowExceptions

Exception or error:

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

How to solve:

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]

Answer:

Create a new array with your ranges, then iterate through the values and through the ranges inside. If the current value is inside the range, add the record to the current range:

<?php
$numbers = [1,1,2,2,2,3,4,4,5,6,6,6,7];
$counts = [];
$counts[] = ["values"=> [1, 3], "records" => []]; // first value in "values" is min, second is max
$counts[] = ["values"=> [4, 5], "records" => []];
$counts[] = ["values"=> [6, 7], "records" => []];
foreach ($numbers as $number) {
    foreach ($counts as $key => &$value) {
        if ($number >= $value["values"][0] && $number <= $value["values"][1]) { // if between the range, add it to the records
            $value["records"][] = $number;
        }
    }
}
echo "<pre>";
foreach ($counts as $count) {
    echo $count["values"][0]." - ".$count["values"][1]." = ".count($count["records"])." elements<br>";
}

Demo

Answer:

I think array_intersect() and range() with sizeof()/count() does a cleaner job for this task. It eliminates the double-conditional.

Code: (Demo)

function count_range($array, $min, $max) {
    return sizeof(array_intersect($array, range($min, $max)));
}

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

echo count_range($array, 1, 3);  // 6 from [1, 1, 2, 2, 2, 3]
echo count_range($array, 4, 4);  // 2 from [4, 4]
echo count_range($array, 2, 7);  // 11 from [2, 2, 2, 3, 4, 4, 5, 6, 6, 6, 7]
  • range() creates a whitelist array of one or more consecutive integers.
  • array_intersect() compares the input array and the whitelist array all at once.
  • sizeof() is just an alias of count() to determine how many elements were retained.

Leave a Reply

Your email address will not be published. Required fields are marked *