Comparison operators
Learn to compare values with ==, ===, !=, <, >, <= and >=.
Comparison operators
To compare two values you use comparison operators: == equal, != not equal, < less than, > greater than, <= less than or equal, >= greater than or equal. The result is always a bool (true or false).
For example, $age >= 18 returns true when the age is greater than or equal to 18. You can use this result in an if condition.
Strict comparison: ===
In PHP, == does a loose comparison: it converts types. "5" == 5 returns true because PHP converts the string to a number. This can sometimes cause surprises.
=== is a strict comparison: both the value and the type must match. "5" === 5 returns false because one is a string and the other is a number. Using === is safer to avoid accidental matches.
Exercise Compare two scores
Write an if with the condition $score1 > $score2. When true, print "high" with echo; otherwise print "low". You must use an else branch.
Show example solution
To compare, write if ($score1 > $score2) { ... } else { ... }.
Example solution:
<?php
$score1 = 85;
$score2 = 70;
// Compare and print
if ($score1 > $score2) {
echo "high";
} else {
echo "low";
}
Test yourself
-
What is the output of var_dump("5" === 5);?
var_dump("5" === 5);- bool(true)
- int(1)
- int(0)
- bool(false)
Show answer
bool(false) — Correct. "5" is a string and 5 is an int; strict comparison returns false.
-
Write the strict equality operator
var_dump("5" ____ 5);Show answer
var_dump("5" === 5); -
Match each operator to its meaning
- ==
- Equal (loose)
- ===
- Equal (strict)
- !=
- Not equal
- <
- Less than