PHP Decision Making
Decision making statements let your program choose what to do, based on a condition. For example, show “Welcome” if a user is logged in, and a login form if not. PHP has these statements: if, if...else, if...elseif...else, switch and match.
if statement
The code inside the braces runs only when the condition is true.
<?php
$age = 20;
if ($age >= 18) {
echo "You can vote.";
}
?>
Output:
You can vote.
if…else statement
<?php
$age = 15;
if ($age >= 18) {
echo "You can vote.";
} else {
echo "You can not vote yet.";
}
?>
Output:
You can not vote yet.
if…elseif…else statement
Use it to check many conditions. PHP runs the first block whose condition is true.
<?php
$marks = 82;
if ($marks >= 90) {
echo "Grade A";
} elseif ($marks >= 75) {
echo "Grade B";
} elseif ($marks >= 50) {
echo "Grade C";
} else {
echo "Fail";
}
?>
Output:
Grade B
Nested if
You can write an if inside another if. Keep it small, because too many levels are hard to read. You can also join conditions with && and ||.
<?php
$age = 25;
$hasLicense = true;
if ($age >= 18 && $hasLicense) {
echo "You can drive.";
}
?>
Output:
You can drive.
switch statement
Use switch when you compare one value with many fixed options. Do not forget break, otherwise PHP continues with the next case. The default runs if nothing matches.
<?php
$day = 3;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
case 3:
echo "Wednesday";
break;
default:
echo "Invalid day";
}
?>
Output:
Wednesday
match expression (PHP 8)
The match expression is a shorter and stricter version of switch. It returns a value, uses strict comparison and needs no break. Read the full chapter: PHP match Expression.
<?php
$day = 3;
echo match ($day) {
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
default => "Invalid day",
};
?>
Output:
Wednesday
Short forms
- The ternary operator for a simple if-else in one line, see PHP Ternary Operator.
- The null coalescing operator
??for default values.
Next chapter: PHP Loops.
| Interview Questions & Answers |
|---|
| No Content Found. |