Automated message based on date

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
bill1one
Forum Newbie
Posts: 8
Joined: Thu May 24, 2007 2:12 pm

Automated message based on date

Post by bill1one »

I am currently using the following code to automatically generate messages for when my business will be closed base don the date of a holiday. This is working fine, but seems inefficient. Is there perhaps a more efficient or concise way to express the same code?

Code: Select all

 
<?php
//set the holidays
$new = "2009-01-01";
$mem = "2009-05-25";
$ind = "2009-07-04";
$lab = "2008-09-01";
$tha = "2008-11-27";
$chr = "2008-12-25";
$todays_date = date("Y-m-d"); 
 
//converts to time
$hol_new = strtotime($new);
$hol_mem = strtotime($mem);
$hol_ind = strtotime($ind);
$hol_lab = strtotime($lab);
$hol_tha = strtotime($tha);
$hol_chr = strtotime($chr);
$today = strtotime($todays_date); 
 
//message
$message = "We will be closed<br />";
 
if ($today <= $hol_new && $today >= $hol_new-7 ) { 
   echo $message . "New Years Day."; 
} 
elseif ($today <= $hol_mem && $today >= $hol_mem-7) { 
   echo $message . "Memorial Day."; 
}
elseif ($today <= $hol_ind && $today >= ($ind-7)) { 
   echo $message  . "Independence Day."; 
}
elseif ($today <= $hol_lab && $today >= $hol_lab-7) { 
   echo $message . "Labor Day.";
}
elseif ($today <= $hol_tha && $today >= $hol_tha-7) { 
   echo $message . "Thanksgiving Day."; 
}
elseif ($today <= $hol_chr && $today >= $hol_chr-7) { 
   echo $message . "Christmas Day."; 
}
?> 
 
Thanks.
-Bill
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: Automated message based on date

Post by Eran »

Maybe something like this?

Code: Select all

 
<?php
$holidays = array(
    '2009-01-01' => 'New Years Day.',
    '2009-05-25' => 'Memorial Day.',
    '2009-07-04' => 'Independence Day.',
    '2008-09-01' => 'Labor Day.',
    '2008-11-27' => 'Thanksgiving Day.',
    '2008-12-25' => 'Christmas Day.'
);
 
$today = time();
$message = "We will be closed<br />";
 
foreach($holidays as $date => $holidayName) {
    $time = strtotime($date);
    if($today <= $time && $today >= $time - (7 * 3600 * 24)) {
        echo $message . $holidayName;
    }
}
 
This way you only have to update the array and not touch the logic if you want to change the data. Also, I assumed the (-7) in your second condition was meant to be taken as seven days before the date, and since those time functions are counting seconds I multiplied it by the number of seconds per day.
Post Reply