Advertisement

Ads

Sunday, December 30, 2018

Control Statement in PHP with Example

PHP Control Statement

What is Control Statement in PHP?

A block of code which decide the execution way of programme according to the value of the given condition.
PHP Control Statement with Example

There are some control statements that PHP supports.

1. PHP if Statement

If a given condition is true, only then if statement will execute.
Syntax:
if(condition) {
block1 of code;
}

if Statement Example: 
<?php
if ($15 > $10)
echo “15 is greater than 10”;
?>

Output:
15 is greater than 10

2. PHP if…else Statement

In PHP, if a statement is executed only when a specified condition is true. It evaluated to its Boolean values. If the condition is FALSE, it’ll ignore it.
Syntax:
if(condition) {
block1 of code
}else {
block2 of code
}

if - else Statement Example: Find a largest number between two numbers using if else statement;
<?php
$first_value = 5;
$second_value = 10;
if($first_value > $second_value) {
echo “$first_value is greater than $second_value”;
} else {
echo  “$second_value is greater than $first_value”;
}
?>
Output:
10 is greater than 5

3. PHP if….elseif….else Statement 

With this statement, you can select one of several blocks of code to be executed.
Syntax:
if (condition)
first blockto be executed if condition is true;
elseif (condition)
Second block to be executed if condition is true;
else
final block to be executed if condition is false;
if -else if else statement Example:
<?php
$d = date("D");
if($d == "Thu"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
} else{
echo "Have a nice day!";
}
?>

Output:
Have a nice day!

4. PHP Switch Statement

It is like IF statements. If you want to select one of several blocks of code to be executed, use the Switch statement.
Syntax:
switch ( )
{
case1
break;
case2
break;
default:
default code
break;
}
?>

PHP Switch case Statement Example:
<?php
         $d = date("D");

         switch ($d){
            case "Mon":
               echo "Today is Monday";
               break;

            case "Tue":
               echo "Today is Tuesday";
               break;

            case "Wed":
               echo "Today is Wednesday";
               break;

            case "Thu":
               echo "Today is Thursday";
               break;

            case "Fri":
               echo "Today is Friday";
               break;

            case "Sat":
               echo "Today is Saturday";
               break;

            case "Sun":
               echo "Today is Sunday";
               break;

            default:
               echo “which day is this ?";
         }
      ?>

Output:
Today is Wednesday

No comments:

Post a Comment

Thanks for Reach us !