Branching statements in PHP are used to control the flow of execution based on conditions. The main branching statements in PHP are if
, else
, else if
, and switch
.
PHP Branching Statements
1. if
Statement
The if
statement executes a block of code if a specified condition is true.
// Example of if statement
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
}
// Output: You are eligible to vote.
2. else
Statement
The else
statement executes a block of code if the condition in the if
statement is false.
// Example of if-else statement
$age = 16;
if ($age >= 18) {
echo "You are eligible to vote.";
} else {
echo "You are not eligible to vote.";
}
// Output: You are not eligible to vote.
3. else if
Statement
The else if
statement checks multiple conditions. It executes different blocks of code depending on which condition is true.
// Example of if-elseif-else statement
$grade = 85;
if ($grade >= 90) {
echo "A grade";
} elseif ($grade >= 80) {
echo "B grade";
} else {
echo "C grade";
}
// Output: B grade
4. switch
Statement
The switch
statement is used when you want to compare a variable with multiple possible values. It’s especially useful as an alternative to multiple if
statements.
// Example of switch statement
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week.";
break;
case "Friday":
echo "Almost weekend!";
break;
case "Sunday":
echo "Weekend!";
break;
default:
echo "Have a great day!";
}
// Output: Start of the week.
Conclusion
Branching statements are essential in controlling the execution flow of a program based on conditions. In PHP, the if
, else
, else if
, and switch
statements offer flexibility to make code more dynamic and responsive.