if-else Statement
Explore how to implement the if-else statement in PHP to manage decision-making in your code. Understand the syntax, best practices like using braces, and how to handle nested if statements for complex conditions. This lesson helps you write clearer conditional logic for your PHP programs.
We'll cover the following...
Conditionals in PHP
Programs often need to make decisions based on different inputs or conditions. In PHP, these decisions are handled using conditionals. One of the simplest and most useful conditionals in PHP is the if-else statement.
if and else in PHP
Let’s start by taking a look at an example which checks if a variable a is greater than or less than b. In this example, assume that a and b are not equal, so one of the two branches will always execute:
The figure below illustrates how the working of the above code snippet using a flow chart:
Explanation
Line 4:
-
In this line note that there is space between the keyword
ifand the opening parenthesis. -
Inside the parentheses is the condition; in this case, it is a comparison using greater than operator between two values.
-
It is a good practice to use the same type of arguments (not comparing floating-point values to characters).
-
Note also the left curly brace
{. This symbol denotes a block of multiple lines of code. Without it, the conditional would only refer to the statement immediately following it. -
It is a good practice to always use the braces.
Line 6:
- This comment represents the body of the conditional statement.
Line 8:
-
The right curly brace is essential; it matches the opening brace on line 4 and signals the end of the
ifbody. -
This line is optional. If there is a sort of “default” behavior that should be carried out, it would be placed here.
-
The
elseclause does not belong by itself, only directly following anifclause.
Line 10:
- This is the body of the
elseclause.
Line 11:
- This curly brace is also essential; it matches the opening brace on line 8 and signals the end of the
elsebody.
The body of the else block can be another if statement. This is known as “nested conditionals” because the conditionals are indeed nested; that is, placed inside of one another.
Nested-If
Here one if-else block is nested within another. One has to be careful in closing the inner if before closing the outer if.
Explanation
In the code block above if
-
condition1is true then-
after executing the execution statement(s), code flows to the
condition2check. -
Based on the result either execution statement(s) of the nested
iforelseare executed.
-
-
condition1is false then- code flows to
elsestatement in line 13 and the execution statements of thiselseget executed.
- code flows to
Now let’s take a look at the if-elseif-else statement, another common way to write conditionals in PHP.