PHP Decision Making

Decision Making statements are used to divert the flow of the control according to some scenarios. You may want to perform some work only when some particular condition is fulfilled.

There are following types of Decision Making statements to manipulate a condition-

1.If statement.

2.If...Else Statement

3.If...ElseIf...Else Statement

4.Switch...case Statement

1.If statement



If statement has one or more conditions combined. The code inside if block executes only when the condition specified in parenthesis of if is satisfied.

Syntax

if(condition)

{

the code to be executed

}


Example

<!DOCTYPE html>

<html>

<body>

<?php

$a=40;

if($a<50)

{

echo "This is first block";

}

if($a>40)

{

echo "This is second block";

}

?>

</body>

</html>


Output



2.If...Else Statement



  • We can use an additional else block along with if block.
  • The code inside the else block is executed only when the condition of if statement is not satisfied.
  • Unlike if statement, Else statement never has a condition written in front of it.
  • Else statement always comes with an If statement.
  • syntax



    if(condition)

    {

    code to be executed when condition is true

    }

    else

    {

    code to be executed when condition is false

    }

    Example



    <!DOCTYPE html>

    <html>

    <body>

    <?php

    $a=40;

    if($a>50)

    {

    echo "This is if block";

    }

    else

    {

    echo "This is else block";

    }

    ?>

    </body>

    </html>

    Output



    3. If...ElseIf...Else



    It gives several options with several conditions. The code of the block whose condition is satisfied will be executed.

    Syntax

    if(condition)

    {

    code

    }

    elseif(condition)

    {

    code

    }

    elseif(condition)

    {

    code

    }

    ...

    else

    {

    code

    }

    Example

    <!DOCTYPE html>

    <html>

    <body>

    <?php

    $a=40;

    if($a>40)

    {

    echo "This is if block";

    }

    elseif($a==40)

    {

    echo "This is elseif block";

    }

    else

    {

    echo "This is else block";

    }

    ?>

    </body>

    </html>

    >Output



    4. Switch...Case statement



    There are different blocks having different codes but only one block is executed according the value given in switch statement.

    Syntax

    switch(x)

    {

    case label1:

    code to be executed when x is equal to label1;

    break;

    case label2:

    code to be executed when x is equal to label2;

    break;

    ...

    default:

    code to be executed when x is not equal to any label;

    }

    Example

    <!DOCTYPE html>

    <html>

    <body>

    <?php

    $a=2;

    switch($a)

    {

    case 1:

    echo "This is case for 1 <br>";

    break;

    case 2:

    echo "This is case for 2 <br>";

    break;

    default:

    echo "This is case for default";

    }

    ?>

    </body>

    </html>

    Output