PHP Decision Making

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.

PHP If Statement

If statement executes a code only upon a specific condition is true.

Syntax

if (condition){
 //code will be executed if specified condition is true
}

PHP If Statement Example

<?php
$age = 20; // student age
if ($age == 20) {
	echo "You are teen ager";
}
?>

This will produce following result

You are teen ager

PHP If....Else Statement

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 If....Else Statement Example

<?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

Else...If Statement

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 Else...If Statement Example

<?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