Comparison operators help you check if two values are equal or different. Loose and strict comparisons decide how carefully PHP checks the values.
0
0
Comparison operators (loose and strict) in PHP
Introduction
Checking if a user input matches a stored password (strict check).
Comparing numbers and strings that might look similar (loose check).
Deciding if two variables hold the same value and type (strict check).
Filtering data where type differences don't matter (loose check).
Syntax
PHP
$a == $b // loose equality $a === $b // strict equality $a != $b // loose inequality $a !== $b // strict inequality
Loose comparison (==, !=) converts types if needed before comparing.
Strict comparison (===, !==) checks both value and type without conversion.
Examples
Loose equality says true because '5' and 5 are equal after type conversion. Strict equality says false because one is integer and the other is string.
PHP
$a = 5; $b = '5'; var_dump($a == $b); // true var_dump($a === $b); // false
Loose equality treats 0 and false as equal. Strict equality sees different types and returns false.
PHP
$x = 0; $y = false; var_dump($x == $y); // true var_dump($x === $y); // false
Loose equality treats null and empty string as different, so returns false. Strict equality checks type and finds them different.
PHP
$m = null; $n = ''; var_dump($m == $n); // false var_dump($m === $n); // false
Sample Program
This program compares variables using loose and strict operators and prints which comparisons are true or false.
PHP
<?php $a = 10; $b = '10'; $c = 20; if ($a == $b) { echo "$a == $b is true\n"; } else { echo "$a == $b is false\n"; } if ($a === $b) { echo "$a === $b is true\n"; } else { echo "$a === $b is false\n"; } if ($a != $c) { echo "$a != $c is true\n"; } else { echo "$a != $c is false\n"; } if ($a !== $b) { echo "$a !== $b is true\n"; } else { echo "$a !== $b is false\n"; } ?>
OutputSuccess
Important Notes
Loose comparison can cause unexpected results if types differ, so use strict comparison when type matters.
Strict comparison is safer for checking exact matches, like passwords or IDs.
Summary
Use == and != for loose comparison that converts types.
Use === and !== for strict comparison that checks type and value.
Strict comparison helps avoid bugs from type juggling.