Comparison pitfalls
Learn the difference between === and == and type coercion pitfalls.
== versus ===
PHP has two equality operators. == does loose comparison: it converts types. === does strict comparison: both value and type must match.
For example, "0" == false returns true because PHP converts the string and compares with false. But "0" === false returns false because a string and a bool are different types. To avoid surprises, prefer ===.
Type coercion pitfalls
Loose comparison makes some surprising conversions. 0 == "abc" returns true because the string becomes 0 when cast to a number. null == false is true and null == 0 is true, but null === false is false.
That is why user input, form submissions and password checks should always use === or !==. Unexpected type conversions can lead to security holes.
Exercise Strict role check
A $role variable is already declared. Write an if with the strict comparison $role === 'admin'; when true, print echo 'welcome'. Do not use ==; use ===.
Show example solution
For strict comparison, write if ($role === 'admin') { ... }.
Example solution:
<?php
$role = 'admin';
// Role check
if ($role === 'admin') {
echo 'welcome';
}
Test yourself
-
What is the output of var_dump("0" == false);?
var_dump("0" == false);- bool(false)
- NULL
- bool(true)
- string(0)
Show answer
bool(true) — Correct. PHP converts '0' to false, so == returns true.
-
Match the equality operators
- ==
- Equal (loose)
- ===
- Equal (strict)
- !=
- Not equal (loose)
- !==
- Not equal (strict)
-
Write the strict equality operator
var_dump("5" ____ 5);Show answer
var_dump("5" === 5);