Else If in PHP with time restrictions

Viewed 64

I'm trying to get this website I'm working on to display a different picture depending on the time of day. I'm using a PHP elseif statement.

I've tried changing over my format for the time to 'G' to get the leading zero's off, I've tried using the entirety of the day 'H:i:s', and I've tried just using 'H' to get the time to trigger the event.

<?php
date_default_timezone_set('America/New_York');
$datetime = new DateTime('now');
$time = $datetime->format('H');
if ($time <= 06 &&$time >= 20) {
  echo '<img src="images/SpringNight.png" class="rounded img-fluid" width="720" height="480">';
}else{
  echo '<img src="images/Spring.png" class="rounded img-fluid" width="720" height="480">';
}
?>

I'm trying to get the first statement in the elseif to pop when it's between 8pm and 6am. It's just outputting the else all day long.

Edit: I think I got it. I tried using "||" in place of the "&&" and it seems to have worked.

<?php
date_default_timezone_set('America/New_York');
$datetime = new DateTime('now');
$time = $datetime->format('H');
if ($time <= 06 || $time >= 20) {
  echo '<img src="images/SpringNight.png" class="rounded img-fluid" width="720" height="480">';
}else{
  echo '<img src="images/Spring.png" class="rounded img-fluid" width="720" height="480">';
}
?>
1 Answers

I'd recommend doing an || (as you said in the comment) as a ternary. And then you can print your HTML without the echo, use the $fileName variable and not have to repeat all the HTML twice.

<?php
date_default_timezone_set('America/New_York');
$datetime = new DateTime('now');
$time = $datetime->format('H');
$fileName = ($time <= 6 || $time >= 20) ? 'SpringNight' : 'Spring';
?>
<img src="images/<?=$fileName?>.png" class="rounded img-fluid" width="720" height="480">
Related