[FIXED] range of numbers from array

Issue

I have an array of sorted numbers, for example:

Array ( 
[0] => 33 
[1] => 34 
[2] => 35 
[3] => 36 
[4] => 66 
[5] => 67 
[6] => 68 
[7] => 69 
[8] => 89 
[9] => 90 
[10] => 91 
[11] => 92 
[12] => 93 
)

In this case, we have the following ranges of numbers:

1) 33-36

2) 66-69

3) 89-93

I want to create an array for each range:

Array1 ( [0] => 33 [1] => 34 [2] => 35 [3] => 36 )

Array2 ( [0] => 66 [1] => 67 [2] => 68 [3] => 69 )

Array3 ( [0] => 89 [1] => 90 [2] => 91 [3] => 92 [4] => 93 )

Solution

<?php

$array = [33,34,35,36,66,67,68,69,89,90,91,92,93];

$min = $array[0];
$currentRange = 0;
$ranges = [];

foreach ($array as $element) {
    if($min+1 < $element) {
        $currentRange++;
    }

    $ranges[$currentRange][] = $element;
    $min = $element;
}

var_dump($ranges);

Output:

array(3) {
  [0]=>
  array(4) {
    [0]=>
    int(33)
    [1]=>
    int(34)
    [2]=>
    int(35)
    [3]=>
    int(36)
  }
  [1]=>
  array(4) {
    [0]=>
    int(66)
    [1]=>
    int(67)
    [2]=>
    int(68)
    [3]=>
    int(69)
  }
  [2]=>
  array(5) {
    [0]=>
    int(89)
    [1]=>
    int(90)
    [2]=>
    int(91)
    [3]=>
    int(92)
    [4]=>
    int(93)
  }
}

Answered By – Pyton

Answer Checked By – Clifford M. (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published