Conditions
Conditions let your code make decisions. An if statement asks a question, and PHP runs one block when the answer is true and another when it is false. This is how a page shows different content for different visitors, or how a form validates what it received.
The shape is familiar from JavaScript: if (condition) { ... } else { ... }. The condition is a comparison like $age >= 18 or a variable that is already true or false. PHP answers with a boolean, and the matching block runs.
Comparisons use the same operators you know: == for equal, != for not equal, > and < for size, >= and <= for size-or-equal. For equality checks that also require the same type, use === and !==. The three-char versions are stricter and catch more bugs.
When one value has many possible answers, switch keeps the code tidy. It compares a value against a list of cases and runs the first match. Each case needs a break, or PHP falls through to the next case and keeps executing.
elseif chains
elseif lets you ask several questions in order. PHP stops at the first true one and skips the rest. This is clearer than nested ifs when the choices are exclusive.
$score = 85;
if ($score >= 90) {
echo "Grade A";
} elseif ($score >= 75) {
echo "Grade B";
} elseif ($score >= 60) {
echo "Grade C";
} else {
echo "Keep trying";
}
Switch statements
switch compares one value against cases. Note that switch uses loose comparison by default, and a missing break makes execution fall through into the next case, which is sometimes intentional and usually a bug.
$day = "mon";
switch ($day) {
case "sat":
case "sun":
echo "Weekend";
break;
case "mon":
echo "Start of the week";
break;
default:
echo "Midweek";
}
Syntax
<?php
$age = 20;
if ($age >= 18) {
echo "Welcome in";
} else {
echo "Too young";
}
?>
== vs === in PHP
== does loose comparison ("5"==5 true), === checks type too. Use === for safety.
if ($a === 5)
Good to know
- if runs a block when its condition is true, else catches the rest.
- elseif chains ask questions in order and stop at the first true one.
- === and !== also compare types, not just values.
- switch matches one value against cases and needs break.