The PHP if
and else
statements let a script decide whether to run a chunk of code based on a condition. The if
statement runs a chunk of code if the condition is true or skips it if the condition is false. if
combined with else
runs one chunk if the condition is true, or the other chunk if the condition is false.
PHP lets you take things further, and chain several decision-making blocks together, with each block having its own condition to test. To do this, you use the elseif
statement.
Syntax of the PHP elseif
statement
The simplest form of an if ... elseif
block has the following structure:
if ( condition1 ) {
// This code is run if condition1 is true
} elseif ( condition2 ) {
// This code is run if condition1 is false and condition2 is true
}
// This code is run anyway
Here’s how it works:
- Firstly, condition1 is tested. If it’s
true
then the first block of code — between theif
andelseif
statements — is run. The PHP engine then skips to the first line of code after the wholeif ... elseif
block (the last line of code in the above example). - If condition1 is
false
then condition2 is tested. If this condition istrue
then the second block of code — between theelseif
statement and the final closing brace — is run. Once again, the PHP engine then skips to the first line of code after theif ... elseif
block. - If condition2 is also
false
then neither blocks of code inside theif ... elseif
block are run. Execution continues with the first line of code after theif ... elseif
block.
You can have as many elseif
blocks as you like. Each condition in turn is tested; if it’s true
then the code in the block is run, otherwise the PHP engine moves onto the next elseif
block:
if ( condition1 ) {
// This code is run if condition1 is true
} elseif ( condition2 ) {
// This code is run if condition1 is false and condition2 is true
} elseif ( condition3 ) {
// This code is run if condition1 and condition2 are false and condition3 is true
}
// This code is run anyway
You can also add an else
block after your elseif
block(s). The else
block is run if all the previous if
and elseif
conditions are false
:
if ( condition1 ) {
// This code is run if condition1 is true
} elseif ( condition2 ) {
// This code is run if condition1 is false and condition2 is true
} else {
// This code is run if neither condition1 or condition2 are true
}
// This code is run anyway
A PHP elseif
example
Here’s an example that uses if
, elseif
and else
:
$numWidgets = 2;
if ( $numWidgets > 2 ) {
echo "We have more than 2 widgets in stock<br />";
} elseif ( $numWidgets < 2 ) {
echo "We have less than 2 widgets in stock<br />";
} else {
echo "We have exactly 2 widgets in stock<br />";
}
echo "Number of widgets: $numWidgets<br />";
This code displays:
We have exactly 2 widgets in stock Number of widgets: 2
Now you know how to use the PHP elseif
statement to construct quite complex decision-making code. Happy PHP programming!
Leave a Reply