Page 96 - Beginning PHP 5.3
P. 96
Part II: Learning the Language
echo “<h1>Good evening!</h1>”;
} else {
echo “<h1>Good night!</h1>”;
}
$leapYear = false;
if ( ( ( $year % 4 == 0 ) && ( $year % 100 != 0 ) ) || ( $year % 400 == 0 ) )
$leapYear = true;
echo “<p>Did you know that $year is” . ( $leapYear ? “” : “ not” ) . “ a leap
year?</p>”;
?>
</body>
</html>
The script displays a greeting based on the current time of day, and also lets you know whether the
current year is a leap year. To run it, simply visit the script’s URL in your Web browser. You can see a
sample output in Figure 4-1.
Figure 4-1
How It Works
After displaying an XHTML page header, the script sets two variables: $hour, holding the current
hour of the day, and $year, holding the current year. It uses PHP’s date() function to get these two
values; passing the string “G” to date() returns the hour in 24-hour clock format, and passing “Y”
returns the year.
You can find out more about the workings of the date() function in Chapter 16.
Next, the script uses an if...elseif...else construct to display an appropriate greeting. If the
current hour is between 5 and 12 the script displays “Good morning!”; if it’s between 12 and 18 it
displays “Good afternoon!” and so on.
Finally, the script works out if the current year is a leap year. It creates a new $leapYear variable, set
to false by default, then sets $leapYear to true if the current year is divisible by 4 but not by 100, or
if it’s divisible by 400. The script then outputs a message, using the ternary operator (?) to insert the
word “not” into the message if $leapYear is false.
58
9/21/09 8:52:08 AM
c04.indd 58 9/21/09 8:52:08 AM
c04.indd 58