PHP Tutorials - Herong's Tutorial Examples - v5.17, by Herong Yang
"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 2003 (c) HerongYang.com. All Rights Reserved. # 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:
herong> \php\php IfStatements.php 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
Table of Contents
Introduction and Installation of PHP
PHP Data Types and Data Literals
Variables, References, and Constants
Expressions, Operations and Type Conversions
►Conditional Statements - "if" and "switch"
Loop Statements - "while", "for", and "do ... while"
Function Declaration, Arguments, and Return Values
Interface with Operating System
Introduction of Class and Object
Integrating PHP with Apache Web Server
Retrieving Information from HTTP Requests
Creating and Managing Sessions in PHP Scripts
Sending and Receiving Cookies in PHP Scripts
Controlling HTTP Response Header Lines in PHP Scripts
MySQL Server Connection and Access Functions
Functions to Manage Directories, Files and Images
SOAP Extension Function and Calling Web Services
SOAP Server Functions and Examples
Localization Overview of Web Applications
Using Non-ASCII Characters in HTML Documents
Using Non-ASCII Characters as PHP Script String Literals
Receiving Non-ASCII Characters from Input Forms
"mbstring" Extension and Non-ASCII Encoding Management
Managing Non-ASCII Character Strings with MySQL Servers
Parsing and Managing HTML Documents
Configuring and Sending Out Emails
Managing PHP Engine and Modules on macOS