PHP Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 3.00

"if" Statement Examples

This section provides a tutorial example on how to use different types of 'if' statements to control code executions.

To help us understand how "if" statements work, I wrote the following the tutorial example PHP script:

<?php # IfStatements.php
# Copyright (c) 2003 by Dr. Herong Yang. http://www.herongyang.com/
# 

   print("\n Single-statement \"if\":\n");
   $isNewYear = TRUE;
   if (isNewYear) print("    Happy New Year!\n");

   print("\n Multi-statement \"if\":\n");
   $hasError = TRUE;
   if ($hasError) {
      print("    Open the log file.\n");
      print("    Write an error message.\n");
      print("    Close the log file.\n");
   }
   
   print("\n \"if ... else\" statement:\n");
   $login = "Herong";
   if ($login == "Admin") {
      print("    Display the delete button.\n");
      print("    Display the edit button.\n");
   } else {
      print("    Display the view button.\n");
   }
   
   print("\n \"if ... elseif\" statement:\n");
   $dateInfo = getdate();
   $wDay = $dateInfo["wday"];
   $weekDay = $dateInfo["weekday"];
   $openHours = "open";
   if ($wDay == 0) {
      $openHours = "closed";
   } elseif ($wDay >= 1 && $wDay <= 5) {
      $openHours = "open from 9:00am to 9:00pm";
   } elseif ($wDay == 6 ) {
      $openHours = "open from 9:00am to 5:00pm";
   } else {
      $openHours = "not at here";
   }
   print("    Today is: $weekDay\n");
   print("    The library is $openHours\n");
?>

If you run this sample script, you should get:

 Single-statement "if":
    Happy New Year!

 Multi-statement "if":
    Open the log file.
    Write an error message.
    Close the log file.

 "if ... else" statement:
    Display the view button.

 "if ... elseif" statement:
    Today is: Sunday
    The library is closed

Last update: 2005.

Sections in This Chapter

"if" Statements

"if" Statement Examples

"switch" Statements

"switch" Statement Examples

Dr. Herong Yang, updated in 2009
"if" Statement Examples