1

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

3

3 Answers 3

1

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.