PHP if Statement

The IF Statement is a very important feature of any programming language including PHP. Because, when you will drive into the programming world, you will see the footprint of the conditional if statement everywhere even in the smallest programming project. In this tutorial, we will try to cover every aspect of PHP if Statement.

The IF Statement executes the conditional code blocks depending on the conditional values. By default, like many other languages, PHP compares two or more expression and determine a boolean value either TRUE or FALSE. If PHP determines the boolean value TRUE then it will execute the code fragment that exists inside the IF statement. Otherwise, it will execute the else block.

In this tutorial, we will learn PHP IF statement and its syntax in details. We will learn ELSE Statement in the next tutorial.

PHP If Statement Syntax

The basic syntax of PHP if statement would be:

<?php
    if (comparison of two or multiple expression)
        execution statement
?>

or

<?php
    if (comparison of two or multiple expression) {
        execution statement
    }
?>

The following example would show you whether you are adult or not:

<?php
    if ($age => 18) 
        echo "You are adult!";

// Or you can use curly bracs for implementing
// several statements
    if($age => 18) {
        echo "You are adult!";
    }

//Note: here we did not use multiple statement.
//we will see it in the next tutorial
?>

Now, we are pretty clear about PHP if statement, its syntax, and usage. Less do some more fun with PHP if statement.

PHP Nested IF Statement

Nesting is another common feature of many programming languages. In general, nested if statement means,  “An if statement in another if statement” Yes you can use if statement in another if statement and you can use another if statement in the nested if statement and so on.

Let’s see a formal example then you will catch it easily:

<?php
    $a = 4;
    $b = 5;
    $c = 6;
    $d = TRUE;
    if ($d) {
            if($b > $a) {
                if($c > $b) {
                    $a = 102;
                    $d = FALSE;
                    echo $d . "<br/>";
                    echo $a;
                }
            }
        }
?>

Program Output:
102

Now you should understand the concept of nested IF statement in PHP. Note that, other common program feature also can be nested. For example, function nesting, array nesting, object nesting, class nesting, etc. We will discuss every type in the later chapters.

Changing Values Using Conditional IF

Once again, look at the above code. In that code, we have changed the value of the variable $a = 4 to $a = 102 inside the last nested if condition and after echoing the value we got a = 102. That’s mean you can take any kind of actions inside an if condition.

 

 

« Previous Next »