In PHP, decision making statements or conditional statements are the statements which are used to deciding the order of execution of statements based on certain conditions or perform different types of actions based on different actions.
Basically, decision making statements are used while making a decision. For example - If statement executes a code only upon a specific condition is true.
Different types of decision making statements in PHP such as IF statement, IF Else statement,IF Elseif statement, switch case statement etc.
Syntax
if (condition){ //code will be executed if specified condition is true }
<?php $age = 20; // student age if ($age == 20) { echo "You are teen ager"; } ?>
This will produce following result
You are teen ager
We can enhance any decision making process by adding an else statement to the if construction. This allows to run one block of code if an expression is true and a different block of code if the expression is false.
Syntax
if (condition){ //code to be executed if condition is true; } else { //code to be executed if condition is false; }
<?php $age = 21; // student age if ($age < 21) { echo "student age less than 21"; } else { echo "student age greater than 20"; } ?>
This will produce following result
student age greater than 20
We can even combine the else statement with another if statement to make as many alternative choices as we like:
Syntax
if (condition) { //code to be executed if condition is true; } else if (condition) { //code to be executed if condition is true; } else { //code to be executed if condition is false; }
<?php $age = 21; //student age if ($age == 20) { echo "You are teen ager"; } else if ($age > 20 && < 50) { echo "You are adult"; } else { echo "You are old"; } ?>
This will produce following result
You are adult