PHP The if statement

The if Statement

The if construct is allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

Syntax:

if(expr)
    statement

Here, expr is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it.

Example:

The following example would display a is greater than b:

<?php
    $a = 70;
    $b = 50;
    if ($a > $b)
        echo "a is greater than b";
?>

Output:

Tutorialik.com
a is greater than b

If you'd want to have more than one statement to be executed conditionally. there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group with { }.
For example, this code would display a is greater than b if $a is bigger than $b, and would then assign the value of $a into $b:

Example:

<?php
    $a = 70;
    $b = 50;
    if ($a > $b) {
        echo "a is greater than b";
        $b = $a;
    }
?>

Output:

Tutorialik.com
a is greater than b

Note:

If statements can be nested infinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.


Share This Page to Download:

Share to Download

Share This Page on:


Ask Question