What is Control Structure?

A Control Structure is a block of code that decides the execution of program based on the condition given. It is simply a decision making process in programming languages. It controls the flow of program according to conditions.

PHP IF Else

If... then… else is the simple control structure. It checks the condition using boolean logic. If condition true then it will display true portion otherwise display else portion.

  • You have block of code that should be executed only if some conditions is true.
  • In this you have two options and you have to select one.
  • If… then… else if… is used when you have to select more than two options and you have to select one or more option. 

Syntax

<?php

    if (condition true)

    {

/* Write true code here.. */

    }

    else

    {

/* Write false code here.. */

    }

?>

Here,

  • "if (condition true)" is control structure.
  • "Write true code here" is code to be executed if the condition is true.
  • "…else…" executes when the condition is false.
  • "Write false code here" is code to be executed if the condition is false.

Example

<?php

    $num1 = "5"; /* integer */

    $num2 = "10.5"; /* float */

    

    if ($num1 > $num2)

    {

        echo "Snum1 is greater than Snum2";

    }

    else

    {

        echo "Snum2 is greater than Snum1";

    }

?> 

Output

10.5 is greater than 5

PHP Switch Case

Switch…case is similar to If…then…else control structure. It executes only a single block of code depending the value of condition. In this if not any single condition match then default block of code executes.

Syntax

<?php

    switch(condition)

    {

case value:

    /* code to be executed; */

    break;

case value2:

    /* code to be executed; */

    break;

case value3:

    /* code to be executed; */

    break;

default:

    /* code to be execute; */

    break;

    }

?>

Here,

  • "switch(…){…}" is control structure.
  • "case value:case…" are the block of code to be executed depending on the value of condition.
  • "default:" is the block of code to be executed when no condition match. 

Example

<?php

    $month = "Decemner";

    switch ($month)

    {

        case "January":

            echo "Current month is January..";

            break;

        case "February":

            echo "Current month is February..";

            break;

        case "December":

            echo "Current month is December..";

            break;

        default:

            echo "Current month is not available..";

            break;

    }

?>

Output

Current month is December..