0

I've an array like this -

 Array
(
    [16] => 424
    [17] => 404
    [18] => 416
    [21] => 404
    [22] => 456
    [23] => 879
    [28] => 456
    [29] => 456
    [32] => 123
    [35] => 465
)

The output of this array would be

Array
(
    [0] => Array
           (   ['start'] => 16
               ['stop'] => 19
           )
    [1] => Array
           (   ['start'] => 21
               ['stop'] => 24
           )
    [2] => Array
           (
               ['start'] => 28
               ['stop'] => 30
           )
    [3] => Array
           (
               ['start'] => 32
               ['stop'] => 33
           )
    [4] => Array
           (
               ['start'] => 35
               ['stop'] => 36
           )
)

I don't really need the values. Just grouping the keys.

The 'start' value should be the 'start' value itself. Whereas, the 'stop' value should be a consecutive integer.

And if consecutive integer doesn't exist for a particular key(like for [32] and [35]), 'stop' should be the integer+1 (same as above) .

Thank you all for help.

2
  • i dont know if your example is really consistent. for lonely integers shouldnt the stop/start be equal? Commented Jan 5, 2011 at 5:57
  • Sorry, I missed a point. Question updated, please recheck. Commented Jan 5, 2011 at 6:02

1 Answer 1

5
reset($arr);
$lastKey = key($arr);
$ansIndex = -1;
$ans = array();

foreach ($arr as $k=>$v)
{
    if ($k != $lastKey + 1)
    {
         $ansIndex++;
         $ans[$ansIndex]['start'] = $k; 
    }

    $ans[$ansIndex]['stop']  = $k+1;
    $lastKey = $k;
}

EDIT - changed $k to $k+1 for the stop indexes to reflect change in your question
EDIT - noticed i had a line of code within both if and else. taking it out of conditional since it runs regardless.

Sign up to request clarification or add additional context in comments.

4 Comments

This worked. Just a note, why is $lastKey set to -1? Putting reset($arr) and setting $lastKey to key($arr) did the trick. Please update your answer so I can accept it :)
ok sounds good. i just picked -1 as something that could be relied upon to be different
what changes do you want? where is this reset? cant be within the loop. key($arr) === $k at all times, so for clarity sake i wouldnt change one unless you are going to change every time
o nevermind, i see you are just talking about initialization. good idea i like that better than me pulling -1 out of my ass

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.