The if, else, else if and switch statements are used to write decision-making code. In this tutorial you will learn to usePHP If Else Statements.
PHP Conditional Statements
Like most programming languages, PHP also allows you to write code that perform different actions based on the results of a logical or comparative test conditions at run time. This means, you can create test conditions in the form of expressions that evaluates to either true or false and based on these results you can perform certain actions.
There are several statements in PHP that you can use to make decisions:
- The if statement
- The if…else statement
- The if…elseif….else statement
- The switch…case statement
We will explore each of these statements in the coming sections.
The if
Statement
The if statement is used to execute a block of code only if the specified condition evaluates to true. This is the simplest PHP’s conditional statements and can be written like:
Syntax:
if(condition){ // Code to be executed }
Example:
<?php $dcs_first = 10; $dcs_second = 20; if($dcs_first == $dcs_second){ echo "Both are equal....."; } ?>
The if...else
Statement
You can enhance the decision making process by providing an alternative choice through adding an else statement to the if statement. The if…else statement allows you to execute one block of code if the specified condition is evaluates to true and another block of code if it is evaluates to false. It can be written, like this:
Syntax:
if(condition){ // Code to be executed if condition is true } else{ // Code to be executed if condition is false }
Example:
<?php $dcs_first = 10; $dcs_second = 20; if($dcs_first == $dcs_second){ echo "Both are equal....."; } else{ echo "Both are not equal......"; } ?>
The if...elseif...else
Statements
The if…elseif…else a special statement that is used to combine multiple if…elsestatements.
syntax:
if(condition){ // Code to be executed if condition is true } elseif(condition){ // Code to be executed if condition is true } else{ // Code to be executed if condition is false }
Example:
<?php $dcs_first = 10; $dcs_second = 20; if($dcs_first > $dcs_second){ echo "first is greater than second....."; } elseif($dcs_first < $dcs_second){ echo "first is less than second....."; } else{ echo "I dont know the output hahah......"; } ?>
This is the tutorial on how to use PHP If Else Statements.
If you have any question, feel free to ask it at our Forum Section.