php - range of numbers from array

621

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

Answer

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)
  }
}
173

Answer

Solution:

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

People are also looking for solutions to the problem: php - Can someone break down exactly what a breadcrumb is and how to implement it?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.