i

PHP Tutorial

PHP if...else...elseif Statements

If, else and else if are decision making statements that help us to perform actions based on various conditions. In Php, we have below conditional statements.

>If statement

If statement is used when we want to execute the code if a single condition is true. Syntax of if statement is 

if(condition) 

{code to be executed}

For example, if you want to know a person is adult or not, you can write the below php code.

$age = 20

if($age >18)

{

echo “The person is adult”;

}

?>

>If..else statement

If..else statement helps us in a situation where we have a condition, and we want to execute the code if the condition is true and execute another code if the condition is false.

Syntax of If..else statement is as below. 

if(condition)

{ code executed if the condition is true}

else

{code executed if the condition is false}

For example, To know the person is child or adult to decide some fare you can write the below php code. 

$age = 15

if($age>18)

{

echo “Issue Adult fare”;

}

else

{

echo “Issue Child fare”;

}

?> 

>If..elseif..else statement

If..elseif..else statement is used when you have more than two conditions to decide a code to be executed. The if code executes if condition one is true, elseif code is executed if the second condition is true and if all the conditions are false, then else code is executed. The syntax for If..elseif..else statement is as below. 

if (condition) 

{code executed if this condition is true;}

elseif (condition) 

{code executed when first condition is false, and the specified condition is true;}

else

{code to be executed when all conditions are false;}

For example, in the before case only now you want to issue fare based on child, adults and senior citizen then you can write the below code.

$age = 15

if($age<18)

{

echo “Issue Child fare”;

}

elseif($age>18 and $age<60)

{

echo “Issue Adult fare”;       

}

else

{

echo “Issue Senior Citizen fare”;

}

?>