PHP If Condition

Posted by tutor | Posted in PHP Tutorial | Posted on 12-12-2009-05-2008

0

The If Statement

This statement executes a piece of code only when a condition is true.

Syntax

    if (condition) code to be executed if condition is true;
    For eg:

    <html>
    <body>
    <?php
    $d=date(”D”);
    if ($d==”Fri”) echo “Today is Friday!”;
    ?>
    </body>
    </html>

The if…else Statement

This is a two way condition evaluation, in which there are yes and no both lead to different code block.

We just add one else condition in the above if statement.

Syntax

    if (condition)
    code to be executed if condition is true;
    else
    code to be executed if condition is false;
    For eg:

    <html>
    <body>
    <?php
    $d=date(”D”);          if ($d==”Fri”)
    echo “Today is Friday!”;         else
    echo “Today is not Friday!”;
    ?>
    </body>
    </html>

If more than one line should be executed, then the lines should be enclosed within curly braces:

    <html>
    <body>
    <?php
    $d=date(”D”);
    if ($d==”Fri”)
    {
    echo “Hello!<br />”;
    echo “Today is Friday!”;
    }
    ?>
    </body>
    </html>

The if…elseif….else Statement

This construct is used when there are more conditions than just true or false.

When PHP evaluates If…elseif…else statement it first sees if the If statement is true. If that test comes out to be false it then checks the first elseif statement.

If then also the result comes out to be false it will check the next elseif statement, if there exists any more otherwise, it will evaluate the else segment, if one exists.

Syntax

    if (condition)
    code to be executed if condition is true;
    elseif (condition)
    code to be executed if condition is true;
    else
    code to be executed if condition is false;
    For eg:

    <html>
    <body>
    <?php
    $d=date(”D”);        if ($d==”Fri”)
    echo “Today is Friday!”;        elseif ($d==”Sun”)
    echo “Today is Sunday!”;        else
    echo “Today is neither Friday nor Sunday!”;
    ?>
    </body>
    </html>

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.