2.2. Using Conditional Statements
A conditional statement executes a block of statements only when certain conditions are true. Here are two useful types of conditional statements:
An if statement: Sets up a condition and tests it. If the condition is true, a block of statements is executed.
A switch statement: Sets up a list of alternative conditions. It tests for the true condition and executes the appropriate block of statements.
2.2.1. Using if statements
An if statement tests conditions, executing a block of statements when a condition is true.
2.2.1.1. Building if statements
The general format of an if conditional statement is as follows:
if ( condition ) { block of statements } elseif ( condition ) { block of statements } else { block of statements }
The if statement consists of three parts:
if: This part is required. Only one if is allowed. It tests a condition:
If the condition is true: The block of statements is executed. After the statements are executed, the script moves to the next instruction following the conditional statement; if the conditional statement contains any elseif or else sections, the script skips over them.
If the condition is not true: The block of statements is not executed. The script skips to the next instruction, which can be an elseif, an else, or the next instruction after the if conditional statement.
elseif: This part is optional. You can use more than one elseif if you want. An elseif also tests a condition:
If the condition is true: The block ...
Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.