+91 9952732367

PHP conditional statements

PHP Conditional Statements

if statement:

If the specified conditions are true then it executes some statement.

Syntax:


if (expr)
  statement

Example:


<?php
if ($a > $b)
echo "a is bigger than b";
?>

if…else Statement:

If the specified conditions are true then it executes some statement and false then it executes another statement.

Syntax:


if (expr)
{
Statment1 if condition is true;
}
else
{
Statement2 if condition is false;
}

 


<?php
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>

 

if…elseif…else Statement3:

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original ifexpression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif  conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b.

Syntax:


if (expr)
{
Statment1 if condition is true;
}
elseif(expr)
{
Statement2 if condition is true;
}
else
{
Statement3 if all the above condition is false;
}

 


<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>

Switch statement:

The switch statement is similar to a series of IF statements on the same expression.


<span style="font-family: Consolas, Monaco, monospace; font-size: 12px; line-height: 18px;">switch ( $test ) {</span>
<pre>
  case 1 : 
    // Process for $test = 1
    ...
    break;

  case 5 : 
    // Process for $test = 5
    ...
    break;

  default : 
    // Process for all other cases.
    ...

}</pre>

<?php
if ($i == 0) {
echo "i equals 0";
} elseif ($i == 1) {
echo "i equals 1";
} elseif ($i == 2) {
echo "i equals 2";
}

switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
}
?>

Copyright © s3learn.com