0

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 )
0

2 Answers 2

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

Comments

1
sort($data) ; // if array is not always sorted 

$result = array(); // final result
$item = array() ; // current sub-array
$lastElem = null ; // previous number 

foreach($data as $n)
{
    if(is_null($lastElem) or $n == ($lastElem + 1) ) // first numberor current numberfollow the previous one
    {
        // append n to the current sequence
        $item[] = $n ;
    }
    else
    {
        // save current sequence, and create a new one for the next element
        $result[] = $item ;
        $item = array($n);
    }

    $lastElem = $n ;
}

// add the latest item if not empty
if( count($item) > 0)
    $result[] = $item ;

print_r($result);

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.