Skip to main content

PHP Conditional Statements (if, else, elseif & switch) Tutorial

In a programming language, the conditional statement is a key feature which allows us to perform the specific action on the basis of a certain condition. For example, if the user has entered age less than 13 years, then block further operation, etc. With the help of conditional statements, we can control the execution flow of our code. Almost every programming language has the feature of conditional statements. Like the other programming languages, PHP also provides a feature of conditional statements. In this tutorial, we will explore on how to handle conditions in PHP. We will learn to code the PHP conditional statements.

This tutorial will cover following topics:

  • What are the Conditional Statements
  • Basics of Comparison Operators
  • PHP Conditional Statements
  • PHP If Statement
  • PHP Else Statement
  • PHP Else if/elseif Statement
  • PHP Switch Case Statement
  • Different Ways or Alternative syntax of Writing If else & Switch Case in PHP

What are the conditional Statements

Conditional statements are features of programming language which allows us to perform certain computation action on true or false of some specific conditions. Conditional statements are also knows as the conditional expression or conditional constructs. Term conditional statements are usually used in imperative programming where condition change the state of the program, however, the term conditional expression or conditional construct are usually used in functional programming.

Usually, in our programs, we use the conditional statements along with comparison operators to check if statement is true or false. And depending upon the statement correctness different kind of action is performed. For example, if x==y then do something, x != y then do something else. Sometimes we also exit or halt the program execution with the help of conditional statement. For example, stop the form processing if user age is less than 13 years.

In the flow charts, conditional statements are present by using decision box like below:
Conditional Statement Decision BoxThe edges of the of the box will take the flow further towards true of false and depending upon the true or false different kind of action will be performed. Below is the small flowchart example:
Flow Chart

Conditional statements can also be nested like below expression
if condition:
Some Code Statement
else
if condition
some code statement
……
else
some code statement
end if
end if
In the above statements multiple conditions are used and depending upon the condition different coding action is performed.

In the different programming language, different keywords are used. For example, in bash it is if[ x == y ] then; or in c it is if($x ==y ){, etc. In this tutorial, we will learn conditional statement keywords used in PHP programming.

Basics of Comparison Operators

I have personally observed that very less number of beginner programmer first read or understand comparison operators and then try to learn the conditions statements. The Majority of the beginners learn the comparison operator along with the conditional statements, so I have included this topic in my PHP conditional statements tutorial.

Comparison operators are used to comparing two expressions. Depending upon the comparison statement returns true or false.

In this section, we will only learn the basic comparison operators which will be used in the conditional statements. For the complete in-depth of comparison operators, I will explain in a separate post.

List of Comparison Operators

NameKeywordExampleReturnDescription
Equal==$x==$yReturns TRUEIf both X & Y is equal, returns true, comparison happens after typecasting, otherwise returns false
Not Equal!=$x!=$yReturns TRUEIf both X & Y is not equal, returns true, comparison happens after typecasting, otherwise returns false.
Not Equal!=$x!=$yReturns TRUEIf both X & Y is not equal, returns true, comparison happens after typecasting, otherwise returns false.
Not Equal<>$x<>$yReturns TRUEIf both X & Y is not equal, returns true, comparison happens after typecasting.
Identical===$x===$yReturns TRUEIf both X & Y is equal, returns true, no typecasting, both $x & $y have to be of same data type, otherwise returns false.
Not Identical!==$x!==$yReturns TRUEIf both X & Y is not equal or even $x & $y has same value but different data type returns true, otherwise returns false.
Less Than<$x<$yReturns TRUEIf $x is less than $y with strict type checking returns true, otherwise returns false.
Greater Than>$x>$yReturns TRUEIf $x is greater than $y with strict type checking returns true, otherwise returns false.
Less Than or Equal to<=$x<=$yReturns TRUEIf $x is less than or equal to $y returns true, otherwise returns false.
Greater Than or Equal to>=$x>=$yReturns TRUEIf $x is greater than or equal to $y returns true, otherwise returns false.

Basic Examples of Comparison Operators

Following are some basic examples of comparison operators:
Equal
Following is a basic example of equal to:
$x = 1;
$y =1;
$z = $x == $y;
var_dump($z);

In above code $z will be the value true as we have both $x & $y with the same value.
Equal to with type conversion:
$x = 1;
$y =true;
$z = $x == $y;
var_dump($z);

Again the value of $z will be true because $y is a boolean type with value true.

Not Equal:
Following is a basic example of not equal to:
$x = 1;
$y =0;
$z = $x != $y;
var_dump($z);

Value of the variable $z will be true because $x is not equal to $y.
Not equal to with type conversion
$x = 1;
$y =false;
$z = $x != $y;
var_dump($z);

Since $y is false and the type conversion of $y will yield value zero.

Strictly Type equals to or Identical
Now let us take one of the above example of type conversion and use === instead of ==
$x = 1;
$y =true;
$z = $x === $y;
var_dump($z);

Now the same example with only change in operator from == to === has changed the value because $x is integer type and $y is boolean. Although their value after type conversion will be same but since both are of the different data type === will return false.

Less Than
$x = 1;
$y =3;
$z = $x < $y;
var_dump($z);

$z will be true as $x is less than $y
$x = 5;
$y =3;
$z = $x < $y;
var_dump($z);

$z will be false since $x is not less than $y

Greater Than
For the same above example let us change to operator from < to >
$x = 5;
$y =3;
$z = $x > $y;
var_dump($z);

$z will be true in this case since $x is greater than $y.

Less than or Equals to
$x = 5;
$y =5;
$z = $x <= $y;
var_dump($z);

PHP Conditional Statements

In above section, we have explored the basics of conditional statements and comparison operators. Now in this section we will explore how conditional statements works in PHP, high-level overview of conditional statements and then in further sections we will explore each conditional keywords in-depth.

In PHP conditional statements are formed by following elements

  • Conditional construct
  • Expression which returns true or false with conditional construct

Conditional Constructs are if, else, else if, switch, case etc. These construct with the help of decision expression which returns true or false creates a conditional statement in PHP. For example, to perform some action on age of user following code will be created
if($age > $18)
echo ‘Now you are allowed to enter into the site’
In above example of the conditional statement if is the conditional construct and $age > 18 is an expression which return true of $age value is more than 18 which is expression.

PHP If statement

In PHP by using construct if and some expression which either returns true or false we form if conditional statement. Within an if conditional statement we write some fragment of code which only gets executed if the expression returns true. In the case of if construct the expression evaluation should always happen in the boolean.
if (expression)
statement;

PHP If Flow Chart

In the PHP if statement, when the expression will return true the code written in the if statement block will be executed otherwise it will be ignored.

Following is the simple if statement example in PHP:
<?php
$x = 1;
$y = 2;
if($y>$x)
echo 'y is greater than x';

Here Y is less than X which hold true and so above code will always execute the statement echo ‘y is greater than x’; and echo “y is greater than x” on the screen. But at the same time if we will flip the expression operator from greater than to less than in the same statement then it will do nothing as $y will not be less than the $x. Please see below code:

<?php
$x = 1;
$y = 2;
if($y<$x)
echo 'y is greater than x';

Now, in above code the expression $y<$x will return false, therefore the code echo ‘y is greater than x’; will not be executed.

If statement will multiline code block

In above examples, we have seen that only single line of code statement was executed by using the if statement, so the statement was written just below the if construct. But if we need to execute the multiple lines of code by checking the if condition then we need to wrap the code in curly braces like below.

if (expression){
statement1;
statement2;

}

Below is the working PHP example for multiple lines of statement with if:
$x = 1;
$y =2;
if($y>$x){
echo 'y is greater than x';
$x = $y;
}

In above code we are executing following code using the if statement:
echo ‘y is greater than x’;
$x = $y;
Therefore we have wrapped the code in curly braces.

For the readability purpose, you should always use the curly braces even in the single line code which you are executing via if, for example
$x = 1;
$y = 2;
if($y<$x){
echo 'y is greater than x';
}

Nested If Statement

Sometimes you need to put another if statement within an if statement, like first you need to check country of the user and then you need to check the age of the user to display some legal message, then, in this case, you might need nested if statement. In PHP nested if statement is possible.

Nested if statement:
$country = 'USA';
$age = '13';
if($country == 'USA'){
if($age >= 13){
echo 'Hey buddy you are above or equl to 13 from USA';
}
}

Do not use too many nested if statement in your code. It will increate complexity of your code.

Multiple Condition Check in if Statement

Sometimes in a single if statement you need to check the multiple conditions, for example, if the country is India and state is Bihar then you want to show some message to your user. Then in this case you need to build your if expression like $country == ‘india’ && $state == ‘bihar’. For example
if($country == 'India' && $state == 'Bihar'){
echo 'You are at correct page';
}

In above case, we have used logical operator AND(&&  ) this operator return true if both side of its expression is true. So for our example if both $country will be India and the $state will be Bihar then only the complete expression $country == ‘India’ && $state == ‘Bihar’ will return true and code inside the curly brace will be executed. If either of one will be false like $state is not Bihar then && will return false and the code inside the curly brace will not be executed.

Another Example: If we want to check for either of one statement true from multiple conditions in single if then we need to use OR operator or ||. For example:

if($age>=13 ||$country=='USA'){
//Do something
}

PHP Else Statement

In above section, we have explored the if statement which allows us to execute code if the expression used inside the statement is true. But what if we want to execute some code alternate code statements if the conditions used in if statement is false?  The answer is else statement.

The Else statement is used to add alternate code which will be executed if the expression used in if is not true. Else is always an extension to the if statement and can not be used independently. Similarly like if statement else statement can be written down just below else keyword if the single line of code need to execute. In case of multiple line of code curly braces need to be added.

Pseudocode of If else together:

if (expression)
statement;
else
statement;

Or

if (expression){
statement1;
statement2;

}
else{
statement1;
statement2;

}

 

PHP If else flow chart

Else code block will only execute in case of if statement returns false, otherwise, the code written inside the if stement will be ignored. For example:
if($age >= 13){
echo 'Hey Your age is greather than or equals to 13 years';
}
else{
echo 'You are less than 13 years old';
}

In the above code written in the else block will only be executed if the $age variable will be less than 13.

Nested conditions in else statements

Whatever we have written inside the else statement within the curly brace {} is nothing but a bunch of code. So inside the else statement we can write another if as well. For example
if($age >= 13){
echo 'Hey Your age is greater than or equals to 13 years';
}
else{
echo 'You are less than 13 years old';
if($age > 5){
echo 'You are too young';
}
}

The above code is just an extension to our previous else example, where we have added the nested block inside the else statement.

Again, I just wanted to highlight that please avoid using too much-nested statement because nested conditions will increase your code complexity.

PHP Elseif/ else if Statement

In both, if and the else statement we have seen that even combining both if and else can handle a single expression where if will execute the code if statement is true and else will execute the code if statement is false. Now, what if we need another conditional expression within the same flow of code?  The answer is elseif/else if statement.

From the name itself(else if), the elseif/else if is the statement which is another extension to the if statement which allows us to add another if statement in the same conditional structure. Elseif condition will always come in the action only in case of the if statement is false. Also since the elseif itself has the condition, so the code written inside the elseif statement will only get executed when the conditional statement written inside the elseif statement will be true.

Psudo Code:
if (expression){
statement1;
statement2;

}
elseif(expression){
statement1;
statement2;

}
elseif(expression){
statement1;
statement2;

}
else{
statement1;
statement2;

}
PHP If, else, elseif flow chart

If you will see the above pseudo code then you can find that I have used more than one elseif statement. Is it correct? Yes, It is.

You can add multiple elseif/else if statements but the elseif block will be only executed when all proceeding if and elseif block expression will return false.

In case of all elseif and first if condition will return false then else statement will be executed.

Examples of elseif/else if statements with conditions

Simple elseif:
if($age>=13){
echo 'Hey you are above or equeal to 13 ';
}
elseif($age <= 5){
echo 'You are too young';
}
else{
echo 'You are above 5 but less than 13';
}

In Above code the highlighted is the elseif/else if statement with the conditions. If $age will be 13 or greater than 13 then only if code block will be executed and elseif and else block will be ignored. But if $age will be less than 13 then in second step $age will be checked if the value is less than or equal to 5, if this hold true then elseif code block will be executed. If the age is less than 13 but greater than 5 then no any elseif is written for that hence else statement code will be executed.

Multiple elseif
if($age>=13){
echo 'Hey you are above or equeal to 13 ';
}
elseif($age <= 5){
echo 'You are too young';
}
elseif($age > 5 && $age <=10){
echo 'You are between 6-10';
}
elseif($age > 10 && $age <13){
echo 'you are between  11 -12';
}

else{
echo 'You are above 5 but less than 13';
}

elseif or “else if” both are same and you can use above example of elseif as “else if” like below:
if($age>=13){
echo 'Hey you are above or equeal to 13 ';
}
else if($age <= 5){
echo 'You are too young';
}
else if($age > 5 && $age <=10){
echo 'You are between 6-10';
}
else if($age > 10 && $age <13){
echo 'you are between 11 -12';
}
else{
echo 'You are above 5 but less than 13';
}

It is not necessary to use single variable in all elseif/else if statements. You can use different expression or variable in else if statement like below:
if($age>=13){
echo 'Hey you are above or equeal to 13 ';
}
else if($age <= 5){
echo 'You are too young';
}
else if($country == 'USA'){
echo 'You are between 6-10';
}
else{
echo 'You are above 5 but less than 13';
}

PHP Switch Case Statements

Switch case statements are conditional statements which case be used assubstitutee of if else statement only in the case where one variable need to be tested or compaired against different values. Syntex of switch case statement also be cleaner and self explanetory and easy to use.

PHP Switch case statement is similar to C switch case statement like below pseudo code expression
switch($variable){
case constant1:
 statement1;
 statemetn 2;
case constat2:
  statementx;
  statementy;
deault:
 statementA;
 statementB;
}

In PHP switch case we take an expression or variable with switch construct and then with different constant expression in case construct we match the variable value which was taken in the switch. When the value of switch expression get matched, all code statement inside of that particular case and other further cases will be executed.

In PHP similar like c we can define a case with name default, default case will always be executed even if no any case constant match for the switch.

Following is a simple switch case example in PHP:
$age = 10;
$grade = '';
switch ($age) {
case 5;
echo 'You are 5 years old';
$grade = 'Small';
case 7:
echo 'You are 7 years old';
$grade = 'Mid';
case 10:
echo 'You are 10 years old';
$grade = 'Mid+';
case 12:
echo 'You are 12 years old';
$grade = 'Bit Yong';
default:
echo 'You are in default';
$grade = 'default';
}
echo $grade;

Just think of what will happen when above code will be executed. Since the value of the variable $age is 10, the third case will be matched which is case 10. So every statement written in case 10 will be executed. But, along with the statement of case 10 all further statements will also get executed including the default statement. So the output of above program will be:
You are 10 years old (echo from case 10)
You are 12 years old (echo from case 12)
You are in default (echo from case default)
default (Value of variable $grade will first change to Mid+ in case 10 then Bit Young in case 12 and finally default in the case default so it will print default )
What will happen if $age value will be 50 and the switch case statement will be exactly the same?
It will simply print the below:
You are in default
default
Because, no any case will match and only default case will be executed.

Use of Break keyword in switch case

As we have seen that in PHP switch case statement that once case value is matched then all other case statements after the matched case will be executed including the default one.

So what if you only want to execute exclusively the statements which are only in the matching case and return out from the complete switch statement?

This is only possible by use of Break keyword.

Below is the exactly same example used previously, only added break at the end of every case statements
$age = 10;
$grade = '';
switch ($age) {
case 5;
echo 'You are 5 years old';
$grade = 'Small';
break;
case 7:
echo 'You are 7 years old';
$grade = 'Mid';
break;
case 10:
echo 'You are 10 years old';
$grade = 'Mid+';
break;
case 12:
echo 'You are 12 years old';
$grade = 'Bit Yong';
break;
default:
echo 'You are in default';
$grade = 'default';
}
echo $grade;

Now, following is the output of above code:
You are 10 years old
Mid+
This is because $age is equal to 10 which will match case 10 and all code inside case 10 will be executed including break statement, and then break statement will take us out from switch statement.

The break is not a switch case statement keyword, it is a PHP keyword which is used to end the execution of any loop or switch statement.

In PHP switch case you can have multiple cases which can execute the same code statement like below:
$i =2;
switch ($i){
case 0:
case 1:
case 2:
case 3:
echo 'value of i might be 1,2 or 3';
break;
case 4:
echo 'value of i is definitely 4';
break;
default:
echo 'value of i is greater than 4';
}

Type Confusion with switch case in PHP

$i =10;
switch ($i){
case '10':
echo 'Variable i is string with value 10';
break;
case 10:
echo 'Variable i is intiger with value 10';
break;
}

In above example, $i is an integer, but the output of the switch case will be ‘Variable i is the string with value 10’ and it will match case ’10’ instead of case 10.

But we can not say above as bug in PHP system because as the flow of switch starts with the nearest match with type conversion.

The ‘default’ case

In the PHP switch case statement default case can be used to handle the fallback situation where no matching case is found. Although using default case is not necessary. You can write your switch case statement in PHP without default case like below:
$i =2;
switch ($i){
case 2:
case 3:
echo 'value of i might be 1,2 or 3';
break;
case 4:
echo 'value of i is definetly 4';
break;
}

But only one default case can be added in your switch case statement in PHP. Multiple default case will throw an error.

Below code will always throw an error:
$i =2;
switch ($i){
case 2:
case 3:
echo 'value of i might be 1,2 or 3';
break;
case 4:
echo 'value of i is definetly 4';
break;
default:
echo 'this is default';
break;
default:
echo 'this is default 2';
break;
}

Can I write my default case anywhere in my switch statement?
Yes you can. But not a good practice. It will definitely kill you code readability. Like below:
$i =4;
switch ($i){
case 2:
case 3:
echo 'value of i might be 1,2 or 3';
break;
default:
echo 'this is default';
break;
case 4:
echo 'value of i is definetly 4';
break;
}

Different Ways & Alternative syntax of Writing If else & Switch Case in PHP

In previous sections, we have explored what are the conditional statements, how to write if, else, else if and switch case statements in php. We have reviewed different example of if else & switch case. Now in this section we will explore different ways and some alternative syntax of if-else and switch-case in PHP.

The Different Ways in Comparing Value in if-else

At several places we have used == and === to compare the values in the if statements in PHP. One of theme is below

if($age == 13){
echo 'Your Age is 13 years';
}

Now in the same example by mistake you missed one equal sign and written the code like below:

if($age = 13){
echo 'Your Age is 13 years';
}

What will happen?
In this case your if condition will always return true because the expression $age=13 will assign value 13 to $age. Also, this might screwup your further code execution.
Any Solutions?
Yes, You can always use the conditions matching with == in a reverse way like below:

if(13 == $age){
echo 'Your Age is 13 years';
}

In this case, if you will miss one equal to sign like your code will start throwing error, because you can not assign $age value to constant integer 13. So below code will always throw error:

if(13 = $age){
echo 'Your Age is 13 years';
}

This approach is also know as Yoda conditions.

Direct Use of Boolean in if conditions in PHP

In PHP you can pass boolean variable directly in if condition into you if statements like below:

$is_india = true;
if($is_india){
echo 'hello india';
}

Or like

$is_india = true;
if(!$is_india){
echo 'You are not india';
}

You can use other datatype like string or integer also directly in the if statement as by type conversion of the variable in PHP it will execute the condition like below:

$name = '';
if(!$name){
echo 'name is empty';
}

Here $name is string which hold empty value, now if it will be converted into boolean then it will return false.

Type conversion in the if statement is not a good practice. You should avoid.

Alternative syntax for writing if-else and switch-case in PHP

In all of previous examples we have written if-else PHP examples like below:

if($age>13){
//Do Something
}
else{
//Do something
}

If we are create a code in your class, or function like above it is very easy. But now just imagine a case where you need to print you HTML by checking the type like below:

<div class="container">
<?php if($age > 5){?>
<div class="block">Hi Your age is <?php echo $age ?></div>
<?php } else { ?>
<div class="block">You are not authorised</div>
<?php }?>
</div>

Now while degugging the above code it will be quite tedious to find the curly braces. To overcome this situation PHP provides alternative way of writhing if-else statement like below:

<?php
if($age > 5):
//do something
elseif($gender == 'male'):
//do something
else:
//do something
endif;
?>

So let us use the same thing in our previous code and it will be like below:

<div class="container">
<?php if($age > 5):?>
<div class="block">Hi Your age is <?php echo $age ?></div>
<?php else:?>
<div class="block">You are not authorised</div>
<?php endif;?>
</div>

Simillarly for Switch Case PHP provides another way of writhing like below:

switch ($a):
case 0:
//do something;
case 1:
//do something
default:
//Do something
endswitch;

Following are some worth reading tutorial for in-depth of conditional statements:

Download Complete Code Used in the tutorial.

Support Me by Sharing This Article

Ankur Kumar Singh

I am a PHP programmer having some knowledge about Linux. I am always interested in web development and knowledge sharing. I am full time tech evangelist part time human being. :-)

Leave a comment/Ask Question

3 thoughts on “PHP Conditional Statements (if, else, elseif & switch) Tutorial

  1. Great article.. i learnt about php conditional statements completely from this article which helpful to develop the php skills.. thanks a lot for sharing this article to us

shares