facebook youtube pinterest twitter reddit whatsapp instagram

Conditional Statements In PHP

Conditional statements alter the program flow, and by using a conditional flow, you can make your program make choices about what should happen based on certain conditions. We can achieve this by using a logical expression, and an example of such is if-else-statement, switch statement, e.t.c.

Before we get into logical expression, let's understand logical operators and comparison operators.

Logical Operators

Logical operators is a symbol or word that is used to connect two or more expression, and thus produces an output based on the evaluation of the expression. The output produces are either TRUE or FALSE (they are also known as boolean).

Let's see examples of a logical expression:

Example Operator Result
$j and $k And TRUE if both $j and $k are TRUE
$j && $k Higher-Precedence And TRUE if both $j and $k are TRUE
$j or $k Or TRUE if any one of $j or $k returns TRUE
$j || $k Higher-Precedence Or TRUE if any one of $j or $k returns TRUE
$j xor $k Xor (Exclusive Or) TRUE if either $j or $k is TRUE, but not both

When you see the AND notation between two conditions, it returns true only if all the conditions are True, the first condition is checked, and if that is true, it checks the second condition if that is also true.

On the other hand, the OR notation returns true if any one of the conditions returns true. The first condition is always checked but the second condition is checked only if the first condition is returned false.

In the table above, you must have seen the same operator referenced by a symbol, e.g, AND can also be written as && OR can be written as ||, while these are technically the same, the symbolized version has higher precedence than the word version.

When I say something has higher precedence, it means, it would be executed first in an expression with more than one operator. Here is a list of the precedence table if you are interested.

Consider the following example:

<?php

$myVar = true && false;
var_dump($myVar); # Result is false
$myVar = true and false;
var_dump($myVar); # Result is True

The first one would assign false to $myVar because &&/|| have higher precedence than '=' but 'and/or' have lower priority.

Comparison Operator

Comparison operators are generally used to compare two values, it is that simple. Here are some examples:

Example Operator Result
$j == $k Equal TRUE if $j is equal to $k after type juggling
$j === $k Identical TRUE if $j is equal to $k, and they are of the same type
$j != $k Not Equal TRUE if $j is not equal to $k after type juggling
$j !== $k Not Identical TRUE if $j is not equal to $k, or they are not of the same type
$j < $k Less Than TRUE if $j is less than $k
$j > $k Greater Than TRUE if $j is greater than $k
$j <= $k Less Than or Equal To TRUE if $j is less than or equal to $k
$j >= $k Greater Than or Equal To TRUE if $j is greater than or equal to $k

Note: = is not the same as ==, the first one is for assignment, e.g assigning values to a variable, and the latter is for comparison.

The === is only identical if they are of the same type, string '5', is not identical to integer 5.

Now, let's get on to logical expression:

If Statement

The basic syntax of an if statement is as follows:

if (expression)
   statement;

The expression is going to evaluate to True or False, and if the expression is True, it is going execute the statement, if otherwise, the statement will not be executed, it is that simple, let's see an example:

<?php

$j = 5;
$k = 2;

if ($j == $k) {
    echo "j is equals to k";
}

This would run the echo command if the expression is True, in which case, it isn't, let's modify the code:

<?php

$j = 5;
$k = 5;

if ($j == $k) {
    echo "j is equals to k";
}

#
# Output:
#

j is equals to k

Now, you get the idea, it evaluated the statement as the expression is True, which in our case $j is equals to $k. Feel free to test more examples by referencing the logical operator and comparison operator table.

Extending if with else

There are cases where a script or code would be required to continue regardless of the result of the if condition. What to do when it is true, as well as, false. This is where the elseif or else keyword comes to play, it allows the execution of one block of code when the condition is true and another when the condition is evaluated as false.

To extend our already existing code, we can do:

<?php

$j = 5;
$k = 3;

if ($j == $k) {
    echo "j is equals to k";
}
else {
    echo "j is not equals to k";
    }

#
# Output
#

j is not equals to k

So, what we did above is simply if the first statement is not True, do the second statement, but if the first statement is True, it would skip the else code right away.

In addition to else, we also have elseif, and that strings multiple conditions together, for example:

<?php

$j = 5;
$k = 3;

if ($j == $k) {
    echo "j is equals to k";
}
elseif ($j > $k) {
    echo "j is greater than k";
    }
else {
    echo "j is lesser than k";
}

#
# Output
#

j is greater than k

If the first one matches, it would do the first statement, if the second matches, it would execute the second, and if no one of the two matches, it would default to else. In our case, the second expression matches. You can have multiple elseif statements, but make sure you default to else if anything doesn't match. Feel free to test more examples by referencing the logical operator and comparison operator table.

Switch-Case Statements

We previously looked at creating conditional statements using if and else but there are cases where using case statements makes the logic simpler, and clearer.

This is the basic layout of a switch statement:

<?php

switch (value) {
    case value_to_test1:
        statement
    case value_to_test2:
        statement
    default:
        statement
}

We use the function name, switch followed by an argument, which might be a value, and that value is what we are going to be testing through each of a series of test cases. The test cases are listed in a curly brace starting with the case keyword, and what you are testing against. So basically, the switch statement will first expand the expression and then it will try to match it in turn with each specified case. When a match is found, all the statements are executed.

If no match is found, the statement that is defined by the default would be executed, this is similar to the else statement.

Here is an example that checks user grade:

<?php

$grade = 'D';

switch ($grade) {
    case 'A':
        echo "Excellent Result!<br>";
        break;
    case 'B':
        echo "Excellent Result!<br>";
        break;
    case 'C':
        echo "Good Result!<br>";
        break;
    case 'D':
        echo "Fairly Good, You can try better next time<br>";
        break;
    default:
        echo "Not Impressive, but you could do a lot better next year<br>";
        break;
}

#
# Output
#

Fairly Good, You can try better next time

We assigned a value to the variable $gradeso, we need a way to test user grade by using the switch statement, so, all we need to do is to test the variable $grade>and that is why I had switch($grade)and in the case where it is 'A', we execute a statement, in the case where it is 'B', we execute a statement, and so on. If it doesn't match anything we are expecting, we execute the default case.

As you can see, I am enclosing the value cases in a single-quotes, this is because I am testing against a string, if I am testing against integer, you don't need a single quote, e.g:

<?php

$j = 2;

switch ($j) {
    case 0:
        echo "j equals 0";
        break;
    case 1:
        echo "j equals 1";
        break;
    case 2:
        echo "j equals 2";
        break;
}
#
# Output:
#

j equals 2

It tested the case in series, and it then matches case 2, this is like saying, in case $j is 2, print the statement, you get the idea. Note, the way the switch-case statement works in PHP is a bit crazy, if you do not provide the  break;keyword, it would keep matching the other cases, see an example:

<?php

$j = 0;

switch ($j) {
    case 0:
        echo "j equals 0";
    case 1:
        echo "j equals 1";
    case 2:
        echo "j equals 2";
}

#
# Output
#
j equals 0
j equals 1
j equals 2

It would keep matching them in turn, and keep executing the case statement, so, you need to explicitly write the break keyword, which is very annoying, but if you want to write in PHP, you need to bend to PHP rules and syntax, there is nothing much you can do about that.

Now, let's improve on how our grade code, the below is an improved version:

<?php

$grade = 'B';

switch ($grade) {
    case 'A':
    case 'B':
    case 'C':
        echo "Excellent Result!";
        break;
    case 'D':
        echo "Fairly Good, You can try better next time";
        break;
    default:
        echo "Not Impressive, but you could do a lot better next year";
}

If you are in the situation where you would like to execute the same statement for different cases, you can write them one after the order, without using the break keyword, so, in the example above, we tested for Case A, B, and C, and if it matches anything of sort, the echo statements that is related to the Case A, B, and C gets executed once, this is much more faster and better than using if/else statement or by writing the same statement for each cases.

The above code can also be written in an alternative syntax like so:

<?php

$grade = 'B';

switch ($grade):
    case 'A':
    case 'B':
    case 'C':
        echo "Excellent Result!<br>";
        break;
    case 'D':
        echo "Fairly Good, You can try better next time<br>";
        break;
    default:
        echo "Not Impressive, but you could do a lot better next year<br>";
endswitch;

Instead of opening the switch statement with an opening curly bracket, you use a colon, and you end it with endswitch; I prefer this method because, I can properly see where the switch started, and where it ended, feel free to choose your preferred method.

Another good advantage of using a case statement instead of an if/else statement is that the expression you are comparing with is only evaluated once in a switch statement, while in an if/else statement, it keeps on re-evaluating, see the following example:

<?php
$i = 0; # $i is still 0

if(++$i == 3) { # $i woule be incremented, so it is 1
    echo 3;
}
elseif(++$i == 2) { # $i would be incremented, so it is 2, and in that case, it would match
    echo 2;
}
elseif (++$i == 1) {
    echo 1;
}
else {
    echo "No match!";
}

#
# Output:
#

2

As you can see above, it would keep re-evaluating the expression, which is why it matches ++$i == 2, this might not be an issue now, but consider the following example using switch-case:

<?php

$i = 0;

switch (++$i):
    case 3:
        echo 3;
        break;
    case 2:
        echo 2;
        break;
    case 1:
        echo 1;
        break;
    default:
        echo "No Match";
endswitch;

#
# Output:
#
1

The answer of this is 1 because the switch statement would only evaluate once, unlike the if/else statement that would re-evaluate for each cases, this is also good when you have a function that returns a certain value, and you only want to evaluate it once.

So, when should you use either of the two, I'll say use if/else if you want to evaluate several variables to find the first one with an actual value, something like:

$a = 1;
$b = 2;

if ($a > $b) {
echo "a is larger than b";
} elseif ($a < $b) {
echo "a is smaller than b";
}...

There is no way you can do that with a switch as it only accepts a single expression e.g switch(n), but if we think of this, we can implement a logic that uses a Boolean TRUE, in the line of switch(TRUE) which would evaluate each and every cases, see an example:

 

<?php

$i = 2;
$k = 4;

switch (true):
    case ($i > $k):
        echo "i is larger than k";
        break;
    case ($i < $k):
        echo "i is lesser than k";
        break;
    default:
        echo "No Match";
endswitch;
#
# Ouput:
#

i is lesser than k

Switch (true) would keep evaluating, so make sure you have your break keyword in place when an expression matches as I have done above.

While some would argue that this isn't a better construct, imo, it's all about preference, and in fact, this type method is used on a regular occasion when programming in bash, I wrote one here:

https://devsrealm.com/bash/creating-multiple-menus-in-bash-scripts/

Do whatever makes the most sense to you.

So, really, you can perform anything if/else can perform and even better ;)

 

Related Post(s)

  • Building Dependency Injection and The Container from Scratch in PHP

    In this guide, you'll learn about dependency injection and a way to build a simple DIC (Dependency Injection Container) in PHP using PSR-11 from scratch. First, What is an Ordinary Dependency? This

  • Creating a Tiny PHP MVC Framework From Scratch

    In this guide, we would go over creating a tiny PHP MVC Framework, this would sharpen your knowledge on how major frameworks (e.g Codeigniter or Laravel) works in general. I believe if you can unders

  • PHP Pluggable and Modular System – Part 2 (Implementation) [Event Dispatcher]

    In the first series of this guide, we discussed the theoretical aspect of building a pluggable system in PHP, I wrote a bit of code in that guide plus a couple of stuff you should avoid, you can lear

  • Best Way To Implement a Non-Breaking Friendly URL In PHP or Laravel or Any Language

    I was working on the link structure of my new Laravel app, and out of the blue I said: "What would happen if a user changes the slug of a post?" First Attempt - 301 Redirection The first solution I t

  • PHP Pluggable and Modular System - Part 1 (Abstract View) [Observable and Mediator Pattern]

    If there is one thing that is brutally confusing to me ever since I started coding, it would be a way to not only implement a Modular system but a way to make it extensible (adding and removing plugi

  • Object Oriented Programming Intro in PHP

    We recently went through the understanding of functions in PHP, well, that is one way of writing a PHP code, and the other way is using objects. In object-oriented programming, objects include data a