Programs would be dull if they did the same thing every time. Conditions are how code reacts to circumstances: show a discount only to members, reject a form with an empty email field, switch to dark mode after sunset. Each of those choices starts with a question whose answer is a boolean, and the program takes one path or another depending on it.
Conditions are built from comparison operators (==, !=, <, >, <=, >=) and can be joined with logical operators like && and ||.
Example
$temperature = 31;
if ($temperature >= 30) {
echo "Hot day: drink water.";
} elseif ($temperature >= 15) {
echo "Mild weather.";
} else {
echo "Bring a jacket.";
}
The checks run from top to bottom and only the first matching branch executes. At 31 degrees, the second check is never even evaluated. Other languages spell elseif differently: Python uses elif, while JavaScript and Java write else if.
Comparison vs assignment
A single = assigns a value; it does not compare. Writing if ($x = 5) in PHP or JavaScript stores 5 in $x and then treats the result as true, so that branch always runs. Use == to compare, or better still the strict === available in PHP and JavaScript, which also checks that both values share the same type. Under loose comparison, PHP 7 considered 0 == "a" true, and PHP 8 changed it to false. Rules like that are why many developers default to strict equality.
Conditions vs loops
A condition decides whether a block runs once or not at all. A loop relies on a condition too, but re-checks it after every pass and keeps going while it holds. When choosing among many fixed values, such as menu options, a switch statement (or match in PHP 8) can read more clearly than a long if chain.
Learn more
- Try changing
$temperaturein the PHP editor. - PHP course
- Fundamentals course
Last updated