Control flow is how your program makes decisions. Without it, your code runs line by line from top to bottom with no branching. With if, else, and friends, your code adapts based on conditions โ just like real life.
The basic idea: check something, and if it's true, do one thing. If it's false, do something else (or nothing). PHP evaluates expressions as either true or false, and acts accordingly.
if, else, and elseif
The if statement is the simplest conditional. If the condition in parentheses is true, the code block runs. You can chain elseif for multiple conditions and else as a catch-all.
<?php
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
} elseif ($age >= 13) {
echo "You are a teenager.";
} else {
echo "You are a child.";
}
?>
Try it Yourself โ
Comparison Operators
These let you compare values. The most important distinction is between == (loose equality) and === (strict equality). == checks if values are equal after type conversion. === checks if values are equal AND the same type. Always prefer === unless you have a specific reason not to.
<?php
$a = "5"; // string
$b = 5; // integer
var_dump($a == $b); // true โ "5" is converted to 5
var_dump($a === $b); // false โ string vs integer
var_dump($a != $b); // false โ loose not equal
var_dump($a !== $b); // true โ strict not equal
var_dump($a > $b); // false
var_dump($a < $b); // false
var_dump($a >= $b); // true
?>
Logical Operators
Combine multiple conditions with logical operators. && (AND) requires both conditions to be true. || (OR) requires at least one. ! (NOT) flips true to false and vice versa.
<?php
$has_id = true;
$age = 20;
if ($has_id && $age >= 18) {
echo "Welcome to the club!";
}
if ($age < 13 || $age > 80) {
echo "Special pricing applies.";
}
if (!$has_id) {
echo "Please show ID.";
}
?>
The switch Statement
When you have one variable to compare against many possible values, switch is cleaner than a long chain of elseif.
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week!";
break;
case "Friday":
echo "Weekend is near!";
break;
case "Saturday":
case "Sunday":
echo "It's the weekend!";
break;
default:
echo "Just another day.";
}
?>
Don't forget the break. Without it, PHP continues executing the next case โ this is called "fall-through." Sometimes that's intentional, but usually it's a bug.