Insert text depending on time of day and day of week - php

I'm trying to piece together a php script to output different text depending on what day it is and the time of day.
Example:
On weekdays (mon-fri), I would like to output text according to the following periods of time (24H, server time, UTC):
00:00-08:00: "Lorem ipsum"
08:00-13:00: "dolor sit amet"
13:00-15:00: "Pellentesque habitant"
15:00-15:30: "dolor sit amet"
15:30-24:00: "Lorem ipsum"
On weekends (sat-sun), I would like to output the following text in this time period:
00:00-24:00 "Lorem ipsum"
Can anyone help with a php script to do that?
I've already gotten some help over at the css-tricks forum. They supplied this code:
<?php
$date = strtotime("now");
$hour = date("H", $date);
switch($hour) {
case 00:
case 01:
case 02:
case 03:
case 04:
case 05:
case 06:
case 07:
case 08:
$dets = array("img" => "image1.png", "txt" => "Lorem ipsum");
break;
case 09:
case 10:
case 11:
case 12:
case 13:
$dets = array("img" => "image2.png", "txt" => "dolor sit amet");
break;
case 14:
case 15:
case 16:
$dets = array("img" => "image3.png", "txt" => "Pellentesque habitant");
break;
case 17:
case 18:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
$dets = array("img" => "image1.png", "txt" => "Lorem ipsum");
break;
}
echo "<img src='$dets[img]' alt='$dets[txt]' />";
?>
But it works for all days, and only in full hours. I want to be able to specify per half-hour and on a day to day basis.
Still a php-noob so I'm hoping someone can help me.

Drop the switch statement and use a series of if/else statements. The switch isn't going to give you the granularity without being massively verbose.
<?php
function time_str() {
$dow = date('D'); // Your "now" parameter is implied
if ($dow == 'Sat' || $dow == 'Sun') {
// weekend
return 'Lorum Ipsum';
}
// Time in HHMM format
$hm = (int)date("Gi");
if ($hm >= 0 && $hm < 800) return 'Lorem ipsum';
if ($hm >= 800 && $hm < 1300) return 'dolor sit amet';
if ($hm >= 1300 && $hm < 1500) return ...
if ($hm >= 1500 && $hm < 1530) return ...
if ($hm >= 1530 && $hm < 2359) return ...
}
I also have to point out that your switch statement has an extra case that will never be used - 24. There is no 24th hour; after 23:59, the clock wraps back around to 00:00.

That switch is ugly.
Why not something like:
<?PHP
if (date('l') == 'Saturday' || date('l') == 'Sunday')){
echo 'Lorem ipsum';
}else{ //it's a weekday
if (intval(date('H')) < 8){
echo 'Lorem ipsum';
}elseif(/* another expression */){
echo "something else..
}
}

Thanks for all your suggestions. I had a friend (whos a little better at php than me) look at them, and we came up with this solution.
With this, I am able to specify text for different times of the day, and different days of the week, along with having a list of days with it's very own text.
<?php
date_default_timezone_set('Europe/Copenhagen');
// Runs the function
echo time_str();
function time_str() {
if(IsHoliday())
{
return ClosedHoliday();
}
$dow = date('D'); // Your "now" parameter is implied
if ($dow == 'Sat' || $dow == 'Sun') {
// weekend
return Closed();
}
// Time in HHMM
$hm = (int)date("Gi");
switch(strtolower($dow)){
case 'mon': //MONDAY
if ($hm >= 0 && $hm < 800) return Closed();
if ($hm >= 800 && $hm < 1100) return Open();
if ($hm >= 1100 && $hm < 1500) return OpenDelay();
if ($hm >= 1500 && $hm < 1600) return Open();
if ($hm >= 1600 && $hm < 2359) return Closed();
break;
case 'tue': //TUESDAY
if ($hm >= 0 && $hm < 800) return Closed();
if ($hm >= 800 && $hm < 1100) return Open();
if ($hm >= 1100 && $hm < 1500) return OpenDelay();
if ($hm >= 1500 && $hm < 1600) return Open();
if ($hm >= 1600 && $hm < 2359) return Closed();
break;
case 'wed': //WEDNESDAY
if ($hm >= 0 && $hm < 800) return Closed();
if ($hm >= 800 && $hm < 1100) return Open();
if ($hm >= 1100 && $hm < 1500) return OpenDelay();
if ($hm >= 1500 && $hm < 1600) return Open();
if ($hm >= 1600 && $hm < 2359) return Closed();
break;
case 'thu': //THURSDAY
if ($hm >= 0 && $hm < 800) return Closed();
if ($hm >= 800 && $hm < 1100) return Open();
if ($hm >= 1100 && $hm < 1500) return OpenDelay();
if ($hm >= 1500 && $hm < 1600) return Open();
if ($hm >= 1600 && $hm < 2359) return Closed();
break;
case 'fri': //FRIDAY
if ($hm >= 0 && $hm < 800) return Closed();
if ($hm >= 800 && $hm < 1100) return Open();
if ($hm >= 1100 && $hm < 1500) return OpenDelay();
if ($hm >= 1500 && $hm < 1600) return Open();
if ($hm >= 1600 && $hm < 2359) return Closed();
break;
}
}
// List of holidays
function HolidayList()
{
// Format: 2009/05/11 (comma seperated)
return array("2010/05/04","2009/05/11");
}
// Function to check if today is a holiday
function IsHoliday()
{
// Retrieves the list of holidays
$holidayList = HolidayList();
// Checks if the date is in the holidaylist
if(in_array(date("Y/m/d"),$holidayList))
{
return true;
}else
{
return false;
}
}
// Returns the data when open
function Open()
{
return 'Open';
}
// Return the data when closed
function Closed()
{
return 'Closed';
}
// Returns the data when open but with waiting time
function OpenDelay()
{
return 'Open, but with delay';
}
// Returns the data when closed due to holiday
function ClosedHoliday()
{
return 'Lukket pga. helligdag';
}
?>

$hoursandminutes = date("H:m", $date)
switch ($hoursandminutes)
case "08:15":
//do something,
//be aware though that the string representation 08:15 might actually be 8:15 even in 24h format
I'm sure you can figure out how to go about adding day to day functionallity as well. Read up on the date class.

I am using this, its working, but I would also load some text from an external txt file depending on the day of week.
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<META HTTP-EQUIV="refresh" CONTENT="60">
<title>LOUNAS</title>
<style type="text/css">
body {
overflow:hidden;
}
</style>
<script type="text/javascript"><!--
var imlocation = "";
function ImageArray (n) {
this.length = n;
for (var i =1; i <= n; i++) {
this[i] = ' '
}
}
image = new ImageArray(7);
image[0] = 'sunday.jpg';
image[1] = 'monday.jpg';
image[2] = 'tuesday.jpg';
image[3] = 'wednsday.jpg';
image[4] = 'thursday.jpg';
image[5] = 'friday.jpg';
image[6] = 'saturday.jpg';
var currentdate = new Date();
var imagenumber = currentdate.getDay();
document.write('<img src="' + imlocation + image[imagenumber] + '"> style="width:100%;height:100%;" border="0" /');
//--></script></head>
<body bgcolor="#000000">
</body>
</html>

Related

How to know actual working shift with php

I'm trying to identify the current work shift from 3 options (24 hour format)
First shift 06:00 to 13:59
Second shift 14:00 to 21:59
Third shift 22:00 to 05:59
I tried this, but it's not working as expected
$hour = date("0500");
$shift;
if ($hour >= 0600 && $hour <= 1359 ) {
$shift = 1;
}else if($hour >= 14 && $hour <= 2159 )
{
$shift = 2;
}else
{
$shift = 3;
}
Maybe:
$hour = data('H');
if($hour >= 6 && $hour < 14) {
$shift = 1;
} else if($hour >= 14 && $hour < 22) {
$shift = 2;
} else {
$shift = 3;
}
You could try something like this perhaps:
$hour = data('H');
switch( true ){
case ( $hour >= 6 && $hours < 14 ):$shift=1; break;
case ( $hour >=14 && $hour < 22 ):$shift=2; break;
default: $shift=3; break;
}
Put your time in quotes otherwise starting with 0 makes it an octal number
Also stick with one format if you are going to be comparing
$hour = date("Hi", strtotime("05:00"));
$shift;
if ($hour >= "0600" && $hour <= "1359" ) {
$shift = 1;
}else if($hour >= "1400" && $hour <= "2159" ) {
$shift = 2;
}else {
$shift = 3;
}

php echo Open or Closed business hours depending on date or date

I have reviewed the q/a's on here and have not found an answer for what I am trying to do. I want to put a $variable inside of an array, kind of like an echo.
Here is an example:
$days = '"12/25","12/26"';
return array($days);
I am wanting the above to look like this when the PHP page loads, so that the variable loads/echos inside the array
$days = '"12/25","12/26"';
return array("12/25","12/26")
Here is my entire code, it echos Business hours Open or Closed. As you can see, I want to be able to change the holidays dates from the top of the code to prevent from going to bottom of the page inside the code to change it. I have tried, ($holidays) (holidays) ('$holidays')
<?php
$holidays = '"12/25","12/26"';
date_default_timezone_set('America/New_York');
// Runs the function
echo time_str();
function time_str() {
if(IsHoliday())
{
return ClosedHoliday();
}
$dow = date('D'); // Your "now" parameter is implied
// Time in HHMM
$hm = (int)date("Gi");
switch(strtolower($dow)){
case 'mon': //MONDAY adjust hours - can adjust for lunch if needed
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'tue': //TUESDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'wed': //WEDNESDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'thu': //THURSDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'fri': //FRIDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'sat': //Saturday adjust hours
return Closed();
break;
case 'sun': //Saturday adjust hours
return Closed();
break;
}
}
// List of holidays
function HolidayList()
{
// Format: 05/11 (if year/month/day comma seperated for days)
return array($holidays);
}
// Function to check if today is a holiday
function IsHoliday()
{
// Retrieves the list of holidays
$holidayList = HolidayList();
// Checks if the date is in the holidaylist - remove Y/ if Holidays are same day each year
if(in_array(date("m/d"),$holidayList))
{
return true;
}else
{
return false;
}
}
// Returns the data when open
function Open()
{
return 'We are Open';
}
// Return the data when closed
function Closed()
{
return 'We are Closed';
}
// Returns the data when closed due to holiday
function ClosedHoliday()
{
return 'Closed for Holidays';
}
// Returns if closed for lunch
// if not using hours like Monday - remove all this
// and make 'mon' case hours look like 'tue' case hours
function Lunch()
{
return 'Closed for Lunch';
}
?>
To help Clarify, This is the actual working code. It displays "We are Open","We are Closed","Closed for Holidays" depending on the day of the week, time, and holidays. "Closed for Holidays" is only displayed if it is one of those days listed in Holidays. It works fine, but I was trying to change it so that if I wanted to add more days to the Holidays schedule, I could easily do it at the top of the page code, rather than scrolling down. I know lazy, but it was for production purposes.
<?php
date_default_timezone_set('America/New_York');
// Runs the function
echo time_str();
function time_str() {
if(IsHoliday())
{
return ClosedHoliday();
}
$dow = date('D'); // Your "now" parameter is implied
// Time in HHMM
$hm = (int)date("Gi");
switch(strtolower($dow)){
case 'mon': //MONDAY adjust hours - can adjust for lunch if needed
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'tue': //TUESDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'wed': //WEDNESDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'thu': //THURSDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'fri': //FRIDAY adjust hours
if ($hm >= 830 && $hm < 1700) return Open();
else return Closed();
break;
case 'sat': //Saturday adjust hours
return Closed();
break;
case 'sun': //Saturday adjust hours
return Closed();
break;
}
}
// List of holidays
function HolidayList()
{
// Format: 05/11 (if year/month/day comma seperated for days)
return array("12/25","12/26");
}
// Function to check if today is a holiday
function IsHoliday()
{
// Retrieves the list of holidays
$holidayList = HolidayList();
// Checks if the date is in the holidaylist - remove Y/ if Holidays are same day each year
if(in_array(date("m/d"),$holidayList))
{
return true;
}else
{
return false;
}
}
// Returns the data when open
function Open()
{
return 'We are Open';
}
// Return the data when closed
function Closed()
{
return 'We are Closed';
}
// Returns the data when closed due to holiday
function ClosedHoliday()
{
return 'Closed for Holidays';
}
// Returns if closed for lunch
// if not using hours like Monday - remove all this
// and make 'mon' case hours look like 'tue' case hours
function Lunch()
{
return 'Closed for Lunch';
}
?>
$holidays is a "convenience" variable that you are treating as a constant. After the first assignment, it is never changed within your code.
In your previous implementation, $holidays was useful as a string. With your new multi-day holidays requirement, it will be more useful to initialise it as an array of "m/d" strings.
<?php
$holidays = array("12/25", "12/26");
//...
?>
After making the above change, your HolidayList() function becomes redundant, so remove it. Also $holidaysList becomes redundant, so replace every instance of it with $holidays (there is only one instance).
I assume you wanto convert the string into array.
you can first explode them using comma as delimiter, then remove the double quote from the value and put in the days array variable.
<?php
$string = '"12/25","12/26"';
$tmps = explode(',', $string);
foreach($tmps as $tmp)
{
$days[] = str_replace("\"","", $tmp);
}
print_r($days);

PHP if specific business day of week and time echo

The following code works to echo "Open" or "Closed" if time is between 8:15am and 5:30pm. I am trying to make it day specific. How can I incorporate format character 'D' as example, Mon hours 8:15am - 5:30pm .. echo "Open", Sat hours 8:15am - 1:00pm "Open". I want to be able to control echo of Open/Closed by each day and time.
current working code for hours only
<?php
date_default_timezone_set('America/New_York');
$hour = (int) date('Hi');
$open = "yah hoo, we are open";
$closed = "by golly, im closed";
if ($hour >= 0815 && $hour <=1735) {
// between 8:15am and 5:35pm
echo "$open";
} else {
echo "$closed";
}
?>
example of what I am trying to do:
$hour = (int) date('D Hi');
if ($hours >= 0815 && $hour <=1735 && $hour === 'Mon')
{ echo "$open"; }
else { echo "$closed"; }
if ($hours >= 0815 && $hour <=1300 && $hour === 'Sat')
{ echo "$open"; }
else { echo "$closed"; }
another example per The One and Only's answer which looks close to what I am looking for, but this also does not work
<?php
$openDaysArray = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat','Sun');
$thisDate = date('D Hi');
$explode = explode(" ", $thisDate);
$day = $explode[0];
$time = $explode[1];
if (in_array($day, $openDaysArray))
if ($time < 815 || $time > 1730 && $day === 'Mon');
if ($time < 815 || $time > 1730 && $day === 'Tue');
if ($time < 815 || $time > 1730 && $day === 'Wed');
if ($time < 815 || $time > 1730 && $day === 'Thu');
if ($time < 815 || $time > 1730 && $day === 'Fri');
if ($time < 815 || $time > 1730 && $day === 'Sat');
if ($time < 815 || $time > 1730 && $day === 'Sun');
{echo 'Open';}
else {echo 'Closed';}
?>
I'd handle it this way. Set up an array of all your open times. If you know you're closed on Saturday and Sunday, there's really no need to proceed with with checking times at that point, so kill the process there first. Then simply find out what day of the week it is, look up the corresponding opening and closing times in your $hours array, create actual DateTime objects to compare (rather than integers). Then just return the appropriate message.
function getStatus() {
$hours = array(
'Mon' => ['open'=>'08:15', 'close'=>'17:35'],
'Tue' => ['open'=>'08:15', 'close'=>'17:35'],
'Wed' => ['open'=>'08:15', 'close'=>'17:35'],
'Thu' => ['open'=>'08:15', 'close'=>'22:35'],
'Fri' => ['open'=>'08:15', 'close'=>'17:35']
);
$now = new DateTime();
$day = date("D");
if ($day == "Sat" || $day == "Sun") {
return "Sorry we're closed on weekends'.";
}
$openingTime = new DateTime();
$closingTime = new DateTime();
$oArray = explode(":",$hours[$day]['open']);
$cArray = explode(":",$hours[$day]['close']);
$openingTime->setTime($oArray[0],$oArray[1]);
$closingTime->setTime($cArray[0],$cArray[1]);
if ($now >= $openingTime && $now < $closingTime) {
return "Hey We're Open!";
}
return "Sorry folks, park's closed. The moose out front should have told ya.";
}
echo getStatus();
Use a switch statement:
$thisDate = date('D Hi');
$hoursOfOpArray = array("Mon_Open" => "815", "Mon_Close" => "1730", "Tue_Open" => "815", "Tue_Close" => "1730"); //repeat for all days too fill this array
$explode = explode(" ", $thisDate);
$day = $explode[0];
$time = (int)$explode[1];
switch($day) {
case "Sun":
$status = "Closed";
break;
case "Mon":
$status = ($time < $hoursOfOpArray[$day . "_Open"] || $time > $hoursOfOpArray[$day . "_Close"]) ? "Closed" : "Open";
break;
//same as Monday case for all other days
}
echo $status;
This should also work:
echo ($day === 'Sun' || ($time < $hoursOfOpArray[$day . "_Open"]) || ($time > $hoursOfOpArray[$day . "_Close"])) ? "Closed" : "Open";
$o = ['Mon' => [815, 1735], /*and all other days*/'Sat' => [815, 1300]];
echo (date('Hi')>=$o[date('D')][0] && date('Hi')<=$o[date('D')][1]) ? "open": "closed";
Done! And dont ask.
This one works, added remarks to explain as much as possible.
<?php
date_default_timezone_set('America/New_York');
// Runs the function
echo time_str();
function time_str() {
if(IsHoliday())
{
return ClosedHoliday();
}
$dow = date('D'); // Your "now" parameter is implied
// Time in HHMM
$hm = (int)date("Gi");
switch(strtolower($dow)){
case 'mon': //MONDAY adjust hours - can adjust for lunch if needed
if ($hm >= 0 && $hm < 830) return Closed();
if ($hm >= 830 && $hm < 1200) return Open();
if ($hm >= 1200 && $hm < 1300) return Lunch();
if ($hm >= 1300 && $hm < 1730) return Open();
if ($hm >= 1730 && $hm < 2359) return Closed();
break;
case 'tue': //TUESDAY adjust hours
if ($hm >= 830 && $hm < 1730) return Open();
else return Closed();
break;
case 'wed': //WEDNESDAY adjust hours
if ($hm >= 830 && $hm < 1730) return Open();
else return Closed();
break;
case 'thu': //THURSDAY adjust hours
if ($hm >= 830 && $hm < 1730) return Open();
else return Closed();
break;
case 'fri': //FRIDAY adjust hours
if ($hm >= 830 && $hm < 1730) return Open();
else return Closed();
break;
case 'sat': //Saturday adjust hours
return Closed();
break;
case 'sun': //Saturday adjust hours
return Closed();
break;
}
}
// List of holidays
function HolidayList()
{
// Format: 2009/05/11 (year/month/day comma seperated for days)
return array("2016/11/24","2016/12/25");
}
// Function to check if today is a holiday
function IsHoliday()
{
// Retrieves the list of holidays
$holidayList = HolidayList();
// Checks if the date is in the holidaylist - remove Y/ if Holidays are same day each year
if(in_array(date("Y/m/d"),$holidayList))
{
return true;
}else
{
return false;
}
}
// Returns the data when open
function Open()
{
return 'Yes we are Open';
}
// Return the data when closed
function Closed()
{
return 'Sorry We are Closed';
}
// Returns the data when closed due to holiday
function ClosedHoliday()
{
return 'Closed for the Holiday';
}
// Returns if closed for lunch
// if not using hours like Monday - remove all this
// and make 'mon' case hours look like 'tue' case hours
function Lunch()
{
return 'Closed for Lunch';
}
?>

Display text based on time of day PHP

I'm using the following code to show opening and closing times throughout the week however on a Tuesday the time to open is at 10:30. It seems to want to sit at 10 or 11. I've tried 10.5 in the PHP variable, but that's not making a change. Any suggestions?
<?php
date_default_timezone_set('Europe/London'); // set it to the right value
$weAreOpen = areWeOpen(date('l'), date('G'));
if($weAreOpen) {
echo 'We are open for business';
} else {
echo 'We are closed';
}
/**
* Test if we're open for business
* #param string $day - day of week (ex: Monday)
* #param string $hour - hour of day (ex: 9)
* #return bool - true if open interval
*/
function areWeOpen($day, $hour) {
$hour = (int)$hour;
switch($day) {
case 'Monday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Tuesday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Wednesday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Thursday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Friday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Saturday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Sunday':
if($hour >= 10 && $hour < 16) {
return true;
}
break;
}
return false;
}
?>
You should read up on what date('G') actually does in the PHP manual for date(). It gives you the hour in an 24 hour format. So, naturally, there can never be a .5 hour.
To check for half hours you can for example get the minutes from here, but in general there is probably a better solution than to check all parts of the clock individually, e.g. checking if the time of the day is lower or greater than something.
You just need to pass minutes as function parameter and use it in if condition like this
<?php
date_default_timezone_set('Europe/London'); // set it to the right value
$weAreOpen = areWeOpen(date('l'), date('G'), date('i'));
if($weAreOpen) {
echo 'We are open for business';
} else {
echo 'We are closed';
}
/**
* Test if we're open for business
* #param string $day - day of week (ex: Monday)
* #param string $hour - hour of day (ex: 9)
* #return bool - true if open interval
*/
function areWeOpen($day, $hour, $minutes) {
$hour = (int)$hour;
switch($day) {
case 'Monday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Tuesday':
if($hour >= 11 && $hour < 21 || ($hour == 10 && $minutes >= 30)) {
return true;
}
break;
case 'Wednesday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Thursday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Friday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Saturday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Sunday':
if($hour >= 10 && $hour < 16) {
return true;
}
break;
}
return false;
}
?>
You should also send the minutes information to your function and check with it.
$weAreOpen = areWeOpen(date('l'), date('G'), date('i'));
...
...
function areWeOpen($day, $hour, $minutes) {
...
// check the minutes value as well
...
}
You need to incorporate minutes and not only hours if you want to react on times like "10:30". Try this:
<?php
date_default_timezone_set('Europe/London'); // set it to the right value
$weAreOpen = areWeOpen(date('l'), date('G'), date('i'));
if($weAreOpen) {
echo 'We are open for business';
} else {
echo 'We are closed';
}
/**
* Test if we're open for business
* #param string $day - day of week (ex: Monday)
* #param string $hour - hour of day (ex: 9)
* #param string $minute - minute (ex: 42)
* #return bool - true if open interval
*/
function areWeOpen($day, $hour, $minute) {
switch($day) {
case 'Monday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Tuesday':
if(($hour + $minute/60) >= 10.5 && $hour < 21) {
return true;
}
break;
case 'Wednesday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Thursday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Friday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Saturday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Sunday':
if($hour >= 10 && $hour < 16) {
return true;
}
break;
}
return false;
}
?>
You cast your variable to an integer in the very first line of your function:
$hour = (int)$hour;
So any information after the hour number will be lost after that.
Removing that line would solve that.
By the way, I don't see any logic in your function that accounts for the Tuesday opening time.
You should probably decide on a format (real time or floats) first and adapt your logic accordingly. I would probably use a DateTime object to store all the information about the moment you are querying about and would give you the possibility to expand the function for holidays, etc..
I would suggest what others already have, you need to include minutes if you want to check against a half hour. Though, I would also simply the rest of the code:
<?php
$weAreOpen = areWeOpen(date('l'), date('G'), date('i'));
if($weAreOpen) {
echo 'We are open for business';
} else {
echo 'We are closed';
}
/**
* Test if we're open for business
* #param string $day - day of week (ex: Monday)
* #param string $hour - hour of day (ex: 9)
* #param int $min - Minute of the hour
* #return bool - true if open interval
*/
function areWeOpen($day, $hour, $min) {
$hour = (int)$hour;
switch($day) {
case 'Monday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
case 'Saturday':
if($hour >= 9 && $hour < 21) {
return true;
}
break;
case 'Tuesday':
if(($hour >= 11 && $hour < 21) || ($min >= 30 && $hour == 10)) {
return true;
}
break;
case 'Sunday':
if($hour >= 10 && $hour < 16) {
return true;
}
break;
}
return false;
}
?>

php if else statement time schedule

I'm using PHP to schedule images to come up on a website at a specific time. I'm fine until a picture has to come up say at 9:42am and end at 10:42am. a can get top of hours and partial hours ending at top of hour but I can't figure out how to schedule multiple partial hours in a row. This is what I'm using
date_default_timezone_set('America/Los_Angeles');
$h = date('G');
$m = date('i');
$d = date('w');
$year = date('Y');
// MONDAY SCHEDULE
if ($d == 1 && $h >= 0 && $h < 1) { $img = 'opendoor.jpg'; }
else if ($d == 1 && $h >= 13 && $h < 14) { $img = 'newtime.jpg'; }
else if ($d == 1 && $h >= 14 && $h < 15) { $img = 'weekend'; }
else if ($d == 1 && $h >= 15 && $h < 16) { $img = 'today.jpg'; }
else if ($d == 1 && $h >= 16 && $h <= 17 && $m >= 0 && $m < 30) { $img = 'walk.jpg'; }
else if ($d == 1 && $h >= 17 && $h < 19 && $m > 30) { $img = 'new.jpg'; }
else if ($d == 1 && $h >= 19 && $h < 20 && $m < 30) { $img = 'default.jpg'; }
else if ($d == 1 && $h >= 19 && $h < 20 && $m > 30) { $img = 'test.jpg'; }
I followed a very good example given to me for my question, but for no apparent reason, some of the hours work and some doesn't. When I echo $img on one hour the code is printed but on the hour before or after it is ommitted. Here is a partial code of what I'm now doing:
date_default_timezone_set('America/Los_Angeles');
$h = date('G');
$m = date('i');
$d = date('w');
$hhmm = date('H') * 100 + date("i");
$img = key(array_filter(array(
'images/hosts/image1.jpg' => ($d == 0 && $h >= 0 && $h < 1),
'images/hosts/image2.jpg' => ($d == 0 && $hhmm >= 0100 && $hhmm <= 0542 ),
'images/hosts/image3.jpg' => ($d == 0 && $hhmm >= 0542 && $hhmm <= 0600),
'images/hosts/image4' => ($d == 0 && $hhmm >= 0600 && $hhmm < 0630),
'images/hosts/image5' => ($d == 0 && $hhmm >= 0630 && $hhmm < 0800),
'images/hosts/image5.jpg' => ($d == 6 && $h >= 8 && $h < 9)
If you want to compare "partial hours", then it might be best to combine hours and minutes into one value. You can often get away with hours*100+minutes:
$h = date('G');
$m = date('i');
$d = date('w');
$hhmm = data("H") * 100 + date("i");
So $hhmm would be 1230 for 12:30am, or 1942 for 7:42pm. The numbers jump between 1759 and 1800, but that's not an issue since you only want to compare with <= and => within time ranges anyway.
Also I would totally rewrite the if/else chain into an array comparison:
$img = key(array_filter(array(
'opendoor.jpg' => ($d == 1 && $h >= 0 && $h < 1),
'newtime.jpg' => ($d == 1 && $h >= 13 && $h < 14),
...
'partialhours.jpg' => ($hhmm => 2142 && $hhmm <= 2242),
)));
please use switch
switch ($d)
{
case 1:
switch ($h)
{
case 1: $img = 'opendoor.jpg'; break;
case 13: $img = 'newtime.jpg'; break;
case 14: $img = 'weekend.jpg'; break;
case 15: $img = 'today.jpg'; break;
case 16:
if ($m<30) $img = 'walk.jpg';
break;
case 17:
$img = ($m>30) ? 'new.jpg':'walk.jpg';
break;
case 18:
if ($m>30) $img = 'new.jpg';
break;
case 19:
$img = ($m>30) ? 'test.jpg':'default.jpg';
break;
}
break;
}

Categories