1

I am trying to display a message depending on the time of day between four specific times, and I don't understand my error. Below is my code and my error message.

$curtime = date("h:i:sa");
echo $curtime;
if ($curtime >= 5:45:00am and $curtime =< 11:59:59am){
    echo "Good Morning";
}
if ($curtime >= 12:00:00pm and $curtime =< 5:59:59pm){
    echo "Good Afternoon";
}
if ($curtime >= 6:00:00pm and $curtime =< 5:44:59am){
    echo "Good Evening";
}

Error message:

PHP Syntax Check: Parse error: syntax error, unexpected ':' in your code on line 11
luek baja
  • 1,475
  • 8
  • 20
JewGiOh
  • 45
  • 5

1 Answers1

1

The error is from the 5:45:00am text just hanging out there.

You need to create a date object from a string, eg:

$curtime = date_create_from_format("h:i:sa", date("h:i:sa"));
$date1 = date_create_from_format("h:i:sa", '5:45:00am');
$date2 = date_create_from_format("h:i:sa", '11:59:59am');

And then use that date object to compare against the current:

if ($curtime >= $date1 and $curtime <= $date2){
    echo "Good Morning";
}

However, it would be faster to just store the current 24 hour + minutes + seconds in a variable and just use those for comparison

$curtime = date('His');


if ($curtime >= 54500 and $curtime <= 0){
    echo "Good Morning";
}
if ($curtime >= 120000 and $curtime <= 175959){
    echo "Good Afternoon";
}
if ($curtime >= 180000 and $curtime <= 54459am){
    echo "Good Evening";
}
Drew
  • 4,215
  • 3
  • 26
  • 40
  • Hi Drew, thanks for your response. I think I made the changes you suggested, but I am still getting errors. Error: There are 3 control structures that contain a single equal sign '=' instead of != !==, ==, or ===: if ($curtime >= $start1 and $curtime =< $end1){ if ($curtime >= $start2 and $curtime =< $end2){ if ($curtime >= $start3 and $curtime =< $end3){ PHP Syntax Check: Parse error: syntax error, unexpected '<' in your code on line 22 if ($curtime >= $start1 and $curtime =< $end1){. Any ideas? – JewGiOh Sep 25 '20 at 21:50
  • 1
    typo: change `=<` to `<=` – jibsteroos Sep 25 '20 at 21:56
  • Can you edit your post and show us what your code looks like after your edits? – Drew Sep 25 '20 at 21:57
  • You solved my problem many thanks! – JewGiOh Sep 25 '20 at 23:36
  • Glad I could help, can you mark my answer as accepted. – Drew Sep 26 '20 at 00:16