Fun with conditional logic

1. Introduction

In this article, we are learning about the different programming constructs that can help us in implementing conditions and to branch the execution of our programs logically. We will learn about if-else construct, switch statements and ternary operator. Let’s go through them.

2. if-else statements

The if statement tests if a particular condition is true or false and acts upon it accordingly.

$bootsity = 1;
if ($bootsity == 1){
    print "bootsity is equal to 1";
}

The output of this code will be:

bootsity is equal to 1

 

If the conditional statement in the brackets of if statement is true, then the code in if block will get executed else, it will be skipped. In addition to this, we can use else, and the code in else block gets executed only if the condition in if clause is false.

$planet = "mars";

if ($plant == "earth"){
    print "Our home!";
}else{
    print "Somewhere in universe";
}

The above code will print:

Somewhere in universe

3. switch statements

We use the switch statement when we want to compare the value of a particular variable to a pre-defined list of value and then do some actions when the value of variable matches to any of those values.
When using the switch statement, we should use break keyword with precautions. The break keyword makes sure that we don’t execute the code of next available cases.

$x = 5;

switch($x){
    case 1:
        print "x is equal to 1";
    break;
    case 2:
        print "x is equal to 2";
    break;
    case 5:
        print "x is equal to 5";
    break;
    case 7:
        print "x is equal to 7";
    break;
    default:
        print "x have no match";
}

This code outputs:

x is equal to 5

4. The ternary operator

The ternary operator is written as ? : and it works the similar way as the if-else structure.

$x;
$y = 9;

$x = ($y==4) ? 5: 25;

print "x = " . $x;

This outputs:

x = 25

5. Conclusion

In this article, we had a look at different programming constructs that can help us to put in conditions in our programs and maintain multiple execution paths by some pre-defined conditions called logic. In the next article in this series, we will learn how we can do repetitive tasks using loops in our programs.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *