enemetch
enemetch

Reputation: 522

How to check a time array if the single values are in +/- 15 minute range of another time

What should I do to make a 4 digit integer/string to behave (not look) like time?

Consider this code:

$t = 0430;
$timeArray = array('0400', '0415', '0420', '0430', '0440', '0450', '0500', '0600');

Now if I have to search $timeArray for elements which are +/- 15 min from $t I would do this:

foreach($timeArray AS $time){
    if($time <= $t + 15 && $time >= $t - 15){
        return $time;
    }
}

Shouldn't be a problem. I'll get back:

0415, 0420, 0430, 0440

But if $t = 0445 and $t = 0505 I'd obviously miss out on 0500 and 0450 respectively.

Now how would I make $t and/or $timeArray elements to behave like time? That 0500 comes after 0459 not 0460?

Edits:

  1. Logical hacks welcome. Need not be just in PHP unless ofcourse if you are using a PHP predefined function :)
  2. I'm getting "integer time" from a webservice. So if I can convert that into "Time/TimeStamp" that would be great too!
  3. My bad. 4 digit string. Like '0400'

Upvotes: 2

Views: 64

Answers (1)

Rizier123
Rizier123

Reputation: 59701

This should work for you:

First convert all strings into timestampes, by looping through all values with array_map().

After this you can simply loop through your values and check if they are in a 15 minute range.

<?php

    $t = "0430"; 
    $timeArray = array('0400', '0415', '0420', '0430', '0440', '0450', '0500', '0600');

    $timestampes = array_map("strtotime", $timeArray);
    $t = strtotime($t);

    foreach($timestampes as $time){
        if($time <= $t + (15*60) && $time >= $t - (15*60)){
            echo date("H:i:s", $time) . "<br>";
        }
    }

?>

output:

04:15:00
04:20:00
04:30:00
04:40:00

Upvotes: 2

Related Questions