Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check PHP array for consecutive indexes

Tags:

arrays

php

Sorry if the title of the question is unclear, I couldn't sum it up more precisely.

This is the issue:

To begin with, I have an array in this format:

Array ( 
    [0] => 09:00 
    [1] => 10:00 
    [2] => 11:00 
    [3] => 12:00 
    [4] => 13:00 
    [5] => 14:00 
    [6] => 15:00 
    [7] => 16:00 
    [8] => 17:00 
    [9] => 18:00 
) 

Then some of the members are unset, so after that we're left with something like:

Array ( 
    [0] => 09:00 
    [1] => 10:00 
    [6] => 15:00 
    [7] => 16:00 
    [8] => 17:00 
    [9] => 18:00 
) 

As you see, the array represents time slots. Now, what I need to do is eliminate all time slots shorter than 3 hours. So I need to go through the array and, wherever there are less than 3 members of the original array present, take them out too. So in the example above, since 09:00 and 10:00 are not followed by 11:00, I need to take them out and be left with:

Array ( 
    [6] => 15:00 
    [7] => 16:00 
    [8] => 17:00 
    [9] => 18:00 
)  

How do I accomplish this? Logically, I think it might be easiest to check for 3 consecutive indexes, rather then checking the actual times but I'm open to any suggestions.

like image 861
sveti petar Avatar asked Jun 28 '26 08:06

sveti petar


1 Answers

I've solved the problem on my own, and I made it generic so it would work for any duration, not just 3 hours.

$dur=3;  //could be anything
foreach($work_times as $member){
    $key=array_search($member,$work_times);
    $a_ok=0;
    for($options=0;$options<$dur;$options++){
        $thisone=1;
        for($try=$key-$options;$try<$key-$options+$dur;$try++){
            if(!array_key_exists($try,$work_times))
                $thisone=0;
        }
        if($thisone==1)
            $a_ok=1;
    }
    if($a_ok==0)
        unset($work_times[$key]);
}
like image 51
sveti petar Avatar answered Jun 29 '26 23:06

sveti petar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!