I’m trying to make a code that will show two different images depending on what the time is and what day it is.
I want it to show an image that says “open” between 7:25 – 12:40 and 13:30 – 14:10 when it’s between the days monday to friday. On weekends and at any other time it should show the image “closed”.
Here’s the code I’ve been trying to get to work.
<?php
date_default_timezone_set('Europe/Copenhagen');
$h = date('Gi'); //G (timer) = 0 til 23 og i (minutter) = 00 til 59
$d = date('N'); //1 (for mandag) til 7 (for søndag)
// MANDAG
if ($d = '1' && $h >= 745 && $h < 1240) $img = 'images/open.png';
if ($d = '1' && $h >= 1330 && $h < 1410) $img = 'images/open_red.png';
// TIRSDAG
if ($d = '2' && $h >= 745 && $h < 1240) $img = 'images/open.png';
if ($d = '2' && $h >= 1330 && $h < 1410) $img = 'images/open_red.png';
// ONSDAG
if ($d = '3' && $h >= 745 && $h < 1240) $img = 'images/open.png';
if ($d = '3' && $h >= 1330 && $h < 1410) $img = 'images/open_red.png';
// TORSDAG
if ($d = 4 && $h >= 745 && $h < 1240) $img = 'images/open.png';
if ($d = 4 && $h >= 1330 && $h < 1410) $img = 'images/open_red.png';
// FREDAG
if ($d = 5 && $h >= 745 && $h < 1240) $img = 'images/open.png';
// LØRDAG
// SØNDAG
else $img = 'images/closed.png';
?>
<img src="<?php echo $img; ?>">
For some reason it ignores the day variable and simply print out the last entry, that being “fredag” (friday).
If actually falls into a number of the different
ifbranches, but overwrites$imgeach successive time.Your main issue is that you aren’t comparing
$dto things, but rather assigning$dvalues each time. For comparison you want the double equal sign:==as inif ($d == 5 && ...Also, you might consider an if, else if, else ladder instead of a number of if statements. As it stands, if the first
ifstatement is the “correct” one, the$imgwill still be set toclosed.pngbecause it fails the lastifstatement.Had you correctly used an if,else if, else ladder, this wouldn’t happen (and your script would run a bit faster).
TLDR: This should work: