Timmy Balk
Timmy Balk

Reputation: 238

Check if number is in between two numbers with increments

I have a time string and also a range of time with increment.

$start = strtotime('10:00:00');
$end = strtotime('23:30:00');
$increment = 30;

$given = strtotime('10:20:00');

if(if number lands on an incremented number) {
    echo 'success'
} else {
    echo 'fail';
}

In the example, I want to see if $given falls on one of the incremented times between $start and $end. Incremented time means add the $increment to the $start until we get to $end.

So in the example code above, the following numbers are the only numbers that should pass the check:

10:00:00
10:30:00
11:00:00
11:30:00
12:00:00
12:30:00
13:00:00
13:30:00
14:00:00
14:30:00
15:00:00
15:30:00
...
23:30:00

In this case, $given = 10:20:00 so it does not pass the check. I don't want to use a for loop. I want to see if there is any math like checking for the remainder % or something like that.

Upvotes: 1

Views: 382

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

Another way is to create a range with increment, from start to end and see if given is found in that array:

if(in_array($given, range($start, $end, $increment * 60))) {
    echo 'success';
} else {
    echo 'fail';
}

Upvotes: 1

Don't Panic
Don't Panic

Reputation: 41810

Yes, you can use % for this.

First you'll need to convert your increment to seconds.

$increment *= 60;

Then you can find the answer by checking that

  1. The given time is less than the end time, and

  2. The difference between the given time and the start time can be evenly divided by increment (i.e. difference % increment == 0)

if ($given <= $end && 0 == ($given - $start) % $increment) {
    echo 'success';
} else {
    echo 'fail';
}

Upvotes: 3

Related Questions