PHP | How To Perform Different Actions Based On Various Conditions

When we want to submit a form by clicking the Send button or show a warning message next to empty required fields, we use conditional statements.

With the use of conditional statements, we can evaluate conditions and determine which code should be executed.

We create conditional statements using the if, else, elseif, and switch keywords together with comparison operators.

So let’s see them one by one.

The If statement

The syntax:

Syntax of an If statement
(click on the image to open in a new tab)

If the condition in the parentheses evaluates to true, the code will be executed.

For example:

Example of an If Statement
(click on the image to open in a new tab)

Here, if the customer is old enough to drink, thus at least 18 years of age, a welcome message is printed.

NOTE: The curly braces can be omitted entirely if there is only one statement to execute.

In that case, the previous example would be written as:

Example of omitted curly braces.
(click on the image to open in a new tab)

The _If-Else_ statement

But what if the customer, in our example, is not of the right age and we want to display a message regarding the reason for our denial to grant him access to our bar?

We can use the If-Else statement:

If the condition evaluates to true, the code within the if block will be executed, while the code within the else block will only be executed when the condition is false.

Example of an If-Else statement
(click on the image to open in a new tab)

Now, if the customer is too young to be granted access to our bar, we can at least explain the reason with a message!

There are cases when executing either piece of code would not suffice. In these cases we need to use the elseif keyword.

Let’s say we want to respond to a question about age eligibility for driving a car. In certain countries, you can drive a car at 17 if accompanied by a licensed driver at least 25 years old.

(click on the image to open in a new tab)

Here we get two messages in a row. This is because PHP checks both if statements. Even if the first statement has been evaluated to true it won’t stop.

Had we not use an elseif statement but two if statements in a row:

(click on the image to open in a new tab)

Now we have reversed the order of the conditions to check for. The 17 years benchmark is checked first, but it leads to an inaccurate result.

Note: If the conditions are not in the correct order, this could cause an inaccurate result.

Nested If statements

Conditional statements can be nested inside other conditional statements in cases where there are many conditions. In such nested If statements, we can enhance readability with consistent indentation.

Let’s say we want to add another condition in our previous example. With proper indentation and proper nesting, we can avoid the mess of too many conditions:

Nesting If-Else statements
(click on the image to open in a new tab)
 NOTE: PHP accepts spaces between else and if.

The above code could be written as:

PHP accepts spaces between else and if.
(click on the image to open in a new tab)

Nesting is not the only option when dealing with a lot of conditions.

Regarding the previous example, we could remove nesting with the use of elseif statements as some changes in the conditional statements.

Example of multiple If-Else statements without nesting.
(click on the image to open in a new tab)

Our code now is a little cleaner, but not necessarily more readable. Readability has a lot to do with the context. Our code should tell a story that is easily comprehensible by other programmers.

Here, if our primary goal is to answer the question “At what age can a teenager drive a car?“, then the former example is more readable. If we want to answer the question “What are the rights of a teenager regarding driving respective to his/her age?” then the latter is the one more readable.

Alternate syntax for conditional statements

PHP provides an alternative syntax for if/else conditional statements.

The basic change is to replace the opening brace with a colon (:) and the closing brace with the endif statement;

Regarding our previous example, if we used the alternate syntax, it would be:

Example of alternate syntax for conditional statements
(click on the image to open in a new tab)
NOTE: Using a space between if and else is not acceptable in the alternate syntax.
Using a space between if and else results in a Parse Error.
(click on the image to open in a new tab)

The Ternary Operator

The ternary operator offers a sorter syntax for an if-else statement. It is great for simple expressions with clear intent where a boolean expression is expected.

Syntax:

expression1 ? expression2 : expression3;

First we have expression1, which is the condition to check.

If the condition is true, it returns expression2, separated by a question mark (?).

If the condition is false, it returns expression3, separated by a colon (:).

When we need to assign a value to a variable based on a condition, the ternary operator (?) is a convenient alternative to an if statement.

Example of a ternary operator.
(click on the image to open in a new tab)

It is also handy when we are working with HTML elements.

Example of a ternary operator within HTML elements.
(click on the image to open in a new tab)

The Null Coalescing Operator

PHP 7 introduced a new logical operator that is very similar to the ternary operator.

It is the null coalescing operator (??).

This operator returns its first operand if it is not null or undefined. Otherwise it returns its second operand.

Syntax:

$first_operand ?? $second_operand;

The Null Coalescing Operator is in fact syntactic sugar for cases where we need to use a ternary operator along with the isset() method.

The following example uses a ternary operator:

Using ternary operator along with the isset() method.
(click on the image to open in a new tab)

The Switch Statement

In programming, a switch statement is a construct that enables the control flow of a program to be altered based on the value of a variable or expression.

The switch conditional statement evaluates an expression against different cases, with each case returning a single value. The program executes the statements, returning the respective value, when the expression is matched and until the break statement is reached.

There can be a default, optional case denoted with the default statement, which is used when all previous cases remain unmatched.

Syntax:

Syntax of a switch conditional statement.
(click on the image to open in a new tab)

Let’s see an example:

(click on the image to open in a new tab)

If the grade is “A+” (Line 14), the program executes the next statement until it reaches the break statement. This means it’ll execute lines 15 to 18.

If the grade is “A” (Line 15), the program executes lines 16 to 18.

If a grade is neither “A+” nor “A”, the program iterates through the cases, checking from top to bottom, until it finds a case that is satisfied.

If none of the cases is valid, the default case will be executed.

Although my blog doesn’t support comments, feel free to reply via email or X.