Skip to main content
April 15, 2007
Question

Time using switch function

  • April 15, 2007
  • 3 replies
  • 521 views
I am trying to get my php script to say Good morning and then Good afternoon using military time. I can't see to get the script to run properly. Here is what I have, what am I missing.

<?php
$today = date("G");

switch(date("G")){
case(date("G") <= 12):
echo "Good Morining";
break;
case(date("G") >= 13):
echo "Good Afternoon";
default:
echo "Cannot Determine";
}

echo $today;
?>

Thank you for your help.
This topic has been closed for replies.

3 replies

Inspiring
April 15, 2007
AdonaiEchad wrote:
> I am trying to get my php script to say Good morning and then Good afternoon
> using military time. I can't see to get the script to run properly. Here is
> what I have, what am I missing.

There are many mistakes in that script. First of all, if you're
assigning date("G") to a variable ($today), you should be using the
variable instead of constantly repeating it. Secondly, you cannot use
comparisons in a case expression. Only integers, floating-point numbers,
or strings are allowed. Thirdly, even if your switch statement worked
(which it won't), you have omitted break after the second case expression.

http://www.php.net/manual/en/control-structures.switch.php

The solution that Gary has given you is the shortest, but may not be
quite so easy to read if you're not familiar with the conditional operator.

This might be easier to read:

<?php
$hour = date('G');
if ($hour < 12) {
$greeting = 'morning';
}
elseif ($hour < 18) {
$greeting = 'afternoon';
}
else {
$greeting = 'evening';
}
echo "Good $greeting";
?>

--
David Powers, Adobe Community Expert
Author, "Foundation PHP for Dreamweaver 8" (friends of ED)
Author, "PHP Solutions" (friends of ED)
http://foundationphp.com/
April 15, 2007
You are right. First I should of seen the break in the switch statement. I should of used the if statement, I thought the switch would of been easier. Thank you both for your quick response.
Inspiring
April 15, 2007
On Sun, 15 Apr 2007 13:35:55 +0000 (UTC), "AdonaiEchad"
<webforumsuser@macromedia.com> wrote:

>I am trying to get my php script to say Good morning and then Good afternoon
>using military time. I can't see to get the script to run properly. Here is
>what I have, what am I missing.

You seem to be overcomplicating it a bit. Why not just:

<?php
print 'Good '.(date('G')<12?'morning':'afternoon');
?>

Gary
Inspiring
April 15, 2007
On Sun, 15 Apr 2007 13:35:55 +0000 (UTC), "AdonaiEchad"
<webforumsuser@macromedia.com> wrote:

>I am trying to get my php script to say Good morning and then Good afternoon
>using military time. I can't see to get the script to run properly. Here is
>what I have, what am I missing.

You're missing a break after "Good Afternoon".
--
Steve Fleischer
steve at flyingtigerwebdesign dot com
Hong Kong