PHP - Using if statement to Display a Greeting

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 {/* www .ja  va2s  . c o  m*/
          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.

$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