If / Else is a conditional statement where depending on the truthiness of a condition, different actions will be performed.
Note: The {}
brackets are only needed if the condition has more than one action statement; however, it is best practice to include them regardless.
<?php
if (condition) {
statement1;
statement2;
}
Note: You can nest as many statements in an "if" block as you'd like; you are not limited to the amount in the examples.
<?php
if (condition) {
statement1;
statement2;
} else {
statement3;
statement4;
}
Note: The else
statement is optional.
<?php
if (condition1) {
statement1;
statement2;
} elseif (condition2) {
statement3;
statement4;
} else {
statement5;
}
Note: elseif
should always be written as one word.
<?php
if (condition1) {
if (condition2) {
statement1;
statement2;
} else {
statement3;
statement4;
}
} else {
if (condition3) {
statement5;
statement6;
} else {
statement7;
statement8;
}
}
Multiple conditions can be used at once with the "or" (||), "xor", and "and" (&&) logical operators.
For instance:
<?php
if (condition1 && condition2) {
echo 'Both conditions are true!';
} elseif (condition1 || condition2) {
echo 'One condition is true!';
} else (condition1 xor condition2) {
echo 'One condition is true, and one condition is false!';
}
Note: It's a good practice to wrap individual conditions in parens when you have more than one (it can improve readability).
There is also an alternative syntax for control structures
if (condition1):
statement1;
else:
statement5;
endif;
Ternary operators are basically single line if / else statements.
Suppose you need to display "Hello (user name)" if a user is logged in, and "Hello guest" if they're not logged in.
If / Else statement:
if($user == !NULL {
$message = 'Hello '. $user;
} else {
$message = 'Hello guest';
}