elseif statement in PHP



“elseif” statement is used to execute several blocks of if statements. If we want to execute a different statement if the original if statement return FALSE we can use elseif control statement.

Its structure will look like
if (expression 1 )
{
// operation statements 1
}
elseif (expression 2 )
{
// operation statements 2
}
elseif (expression 3 )
{
// operation statements 3
}
else
{
// operation statements 4
}

First the main if statement will execute and if it return FALSE , then “operation statements 1” will be avoided and control will go to the next elseif statement with expression 2. If “expression 2” return FALSE then “operation statements 2” will be avoided and control will go to the next elseif statement with expression 3. If “expression 3” return TRUE then “operation statements 3” will be executed otherwise control will go to else statement and “operation statements 4” will be executed.

See the sample PHP program with elseif statement

<?php
$x = 10;
if ( $x < 5 )
{
  echo " value is less than 5";
}
elseif ( $x < 10 )
{
echo "value is less than 10";
}
elseif ( $x < 15 )
{
echo "value is less than 15";
}
else
{
echo " all the above checking failed and else statement executed";
}

?>

Here the ouput will be
value is less than 15

First if statement will execute ( 10 < 5 ) and surely it will return FALSE.
Then control will go to the next elseif statement ( 10 < 10 ) , and of course it also return FALSE.
Then control will go to the next elseif statement ( 10 < 15 ) and it will return TRUE and the block of code inside that elseif statements will execute and it will display the result “value is less than 15”

Note : Space between elseif statement ( like “else if” ) wont parse by PHP compiler and will return error. Make sure there is no space in elseif in your PHP programs.