You are on page 1of 2

9/5/23, 2:40 AM PHP - Using if statement to Display a Greeting

XM Regulated & Trusted Broker


Enjoy Excellent Trading Conditions, Low Spreads, High Leverage, a
0 Commissions.

XM Sign up

PHP - Using if statement to Display a Greeting


HOME (http://www.java2s.com) /  PHP (php.html) /  Statement (statement.index.html)
/  if statement (if-statement.html)

Introduction
Here's a simple example that demonstrates the if, elseif, and else statements, as well as the ? (ternary) operator.

Demo
<?php

$hour = date( "G" );


$year = date( "Y" );

if ( $hour >= 5 && $hour < 12 ) {


echo "Good morning!";
} elseif ( $hour >= 12 && $hour < 18 ) {
echo "Good afternoon!";
} elseif ( $hour >= 18 && $hour < 22 ) {
echo "Good evening!";
} else {/*from www . j a v a2s . c om*/
echo "Good night!";
}

$leapYear = false;

if ( ( ( $year % 4 == 0 ) && ( $year % 100 != 0 ) ) || ( $year % 400 == 0 ) )


$leapYear = true;

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

$year holds 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.
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.

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)

Previous (using-if-statement-to-check-value-range.html) Next (switch-case.html)

HOME (http://www.java2s.com) | Copyright © www.java2s.com 2016

www.java2s.com/example/php-book/using-if-statement-to-display-a-greeting.html 2/2

You might also like