Professional Documents
Culture Documents
XM Sign up
Introduction
Here's a simple example that demonstrates the if, elseif, and else statements, as well as the ? (ternary) operator.
Demo
<?php
$leapYear = false;
echo "$year is" . ( $leapYear ? "" : " not" ) . " a leap year?";
?>
Result
The script sets two variables: $hour, holding the current hour of the day.
www.java2s.com/example/php-book/using-if-statement-to-display-a-greeting.html 1/2
9/5/23, 2:40 AM PHP - Using if statement to Display a Greeting
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.
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!";
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.
Related Exercise
if statement (if-statement.html)
Using if statement to check value in cookie (using-if-statement-to-check-value-in-cookie.html)
Using nested if statement (using-nested-if-statement.html)
if else statement (if-else-statement.html)
www.java2s.com/example/php-book/using-if-statement-to-display-a-greeting.html 2/2