开发者

How can I check an array for consecutive times?

I have an array of qualified times from my database:

$avail_times = array("9","11","12","13","15","16","17","18");

I want to display 4 consecutive values if they exist, if not I want to continue. For example in the above array, the only place where there are four consecutive numbers that properly follow the one before is 15,16,17,and 18

Thoughts?

This may be a duplicate problem, but I have not found a solution. My situation is a bit different. I need to show only those numbers that are consecutive four or more times. This is what I have come up with, but it is not working properly:

$avail_times = array("9","10","11","13","14","15","16","17","19","20","21","22");

for($i=1, $max = count($times) + 4; $i < $max; $i++)
{
    if ($avail_times[$i] == $开发者_开发问答avail_times[$i + 1] - 1)
    {
        echo $avail_times[$i];
    }
}


This should do you:

$avail_times = array("9","10","11","13","14","15","16","17","19","20","21","22");

$consec_nums = 1;
for($i = 1; $i <count($avail_times); $i++) {
    if($avail_times[$i] == ($avail_times[$i - 1] + 1)) {
        $consec_nums++;
        if($consec_nums == 4) break;
    }
    else {
        $consec_nums = 1;
    }
}
if($consec_nums == 4) {
    echo "found: {$avail_times[$i-3]}, {$avail_times[$i-2]}, {$avail_times[$i-1]}, {$avail_times[$i]}\n";
}

And a few notes:

  1. array indexing starts at 0, when your for loop starts with $i = 1, you are skipping the first element. Notice that while I start at $i=1, I am comparing $avail_times[$i] and $avail_times[$i-1] so I do cover $avail_times[0].

  2. I don't know what you're doing with $max = count($times). You never define $times.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜