PHP elseif statement



In the last chapter we have studied the if-else statement in PHP. In this tutorial we are learning the elseif statement,

PHP elseif statement :

If we need to execute some code for several conditions then elseif statement is used.

if (condition)
  Executed if condition is true;
elseif (condition)
  Executed if condition is true;
else
  Executed if condition is false;

Example : PHP

<html>
<body>

<?php
$curr_date = date("D");
	
if ($curr_date == "Sun")
   echo "Today is Sunday"; 
elseif ($curr_date == "Sat")
   echo "Today is Saturday";
else
   echo "Today is week day"; 
?>

</body>
</html>

Output :

Today is Sunday

Explanation :

In this example we have used elseif statement for multiple conditions. So firstly following condition will be checked –

if ($curr_date == "Sun")

If this condition is true then part inside the if block will be executed. If the condition specified is false then next condition specified in the elseif block will be executed.

elseif ($curr_date == "Sat") 

If none of the condition specified inside the if block is executed then finally else will be executed.

Note :

We must put condition after the elseif.

if ($cdate == "Sun")
   echo "Today is Sunday"; 
elseif
   echo "Today is Saturday";
else
   echo "Today is week day";

elseif structure must have else statement –

if ($cdate == "Sun")
   echo "Today is Sunday"; 
elseif
   echo "Today is Saturday";

If we have put elseif statement in the code then we must provide else statement after all the elseif blocks.