HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Check if the shop is open or closed

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theopenclosedshopcheck

Problem

The working hours are saved in Database like

{"1" : "11:00 - 14:30", "2" : "17:30 - 23:00"}


Now i wrote a function like, which test is the shop is opened or close at the moment. Can someone please suggest if there is a better way to do this? And how i can check if the timing are like

{"1" : "11:00 - 14:30", "2" : "17:30 - 02:00"}


Where 02:00 o clock is next day's time.
here is my funciton.

$working_hours = json_decode('{"1" : "11:00 - 14:30", "2" : "14:39 - 23:00"}');
$is_open = false;
$time = time();

foreach ($working_hours as $key=>$value)
{
   $working_hour = explode(" - ", $value);
   $from = strtotime($working_hour[0]);
   $to = strtotime($working_hour[1]);

   if ($time >= $from && $time <= $to)
   {
       $is_open = true;
       break;
   }    
}

echo "\n***********************";
echo "\n". date("d.m.Y H:i", $time);

if($is_open)
   echo "\nOpend";
else
   echo "\nClosed";

echo "\n***********************";

Solution

Easiest solution (to the time problem) is to change your logic (just a tiny bit).

if ($time >= $from && $time <= $to)


To:

if (($to > $from && ($time >= $from && $time = $from || $time <= $to)))


You just change whether to restrict the time to be between the two, or to restrict it to be greater than one or less than the other in the case that the $to time is less than $from.

As far as cleaning up your code: this is about as idiomatic as php will get. Though you should definitely extract this to a function as appropriate.

Code Snippets

if ($time >= $from && $time <= $to)
if (($to > $from && ($time >= $from && $time <= $to)) || 
    ($to < $from && ($time >= $from || $time <= $to)))

Context

StackExchange Code Review Q#23482, answer score: 2

Revisions (0)

No revisions yet.