0
0
PHPprogramming~5 mins

Loose comparison vs strict comparison in PHP

Choose your learning style9 modes available
Introduction

Loose and strict comparisons help you check if two values are equal in different ways. Loose comparison is flexible, strict comparison is exact.

When you want to check if two values are equal but don't care about their types.
When you want to make sure two values are exactly the same, including their types.
When comparing user input that might be a string or number.
When checking if a variable is exactly true or false, not just truthy or falsy.
Syntax
PHP
$a == $b;  // Loose comparison
$a === $b; // Strict comparison

Loose comparison (==) converts types if needed before comparing.

Strict comparison (===) checks both value and type without conversion.

Examples
Loose comparison says true because '5' and 5 are equal after type conversion.Strict comparison 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 comparison treats 0 and false as equal.Strict comparison sees different types and returns false.
PHP
$x = 0;
$y = false;
var_dump($x == $y);  // true
var_dump($x === $y); // false
Loose comparison treats null and empty string as not equal.Strict comparison sees different types and returns false.
PHP
$m = null;
$n = '';
var_dump($m == $n);  // false
var_dump($m === $n); // false
Sample Program

This program shows how loose comparison (==) treats 10 and '10' as equal, but strict comparison (===) does not because of type difference.

It also shows strict comparison returns true when both value and type match.

PHP
<?php
$a = 10;
$b = '10';
$c = 10;
$d = 20;

// Loose comparisons
var_dump($a == $b); // true
var_dump($a == $d); // false

// Strict comparisons
var_dump($a === $b); // false
var_dump($a === $c); // true
OutputSuccess
Important Notes

Loose comparison can lead to unexpected results if you don't know how PHP converts types.

Use strict comparison when you want to avoid bugs caused by type juggling.

Remember that null, false, 0, and empty strings can behave unexpectedly with loose comparison.

Summary

Loose comparison (==) checks if values are equal after converting types.

Strict comparison (===) checks if values and types are exactly the same.

Use strict comparison to avoid surprises and bugs.