PHP strict equality operator
last modified May 18, 2025
In this tutorial, we will delve into the strict equality operator (===) in PHP, a crucial tool for ensuring accurate comparisons and preventing unintended type conversions.
The strict equality operator (===) in PHP is used to compare both the value and the data type of two variables. It returns true only when both the value and type match exactly. This differs from the loose equality operator (==), which allows type juggling—automatically converting types to find a match, often leading to unexpected results. By enforcing strict comparisons, === helps maintain data integrity and prevents hidden bugs caused by implicit type coercion.
Understanding the difference between strict and loose equality is fundamental when handling user input validation, authentication checks, database queries, and conditional logic. Using === ensures reliable comparisons, making your code more predictable and secure.
Basic comparison
The strict equality operator requires both the value and type to match. This is different from loose equality which only compares values after type coercion.
<?php declare (strict_types=1); $num = 5; $str = "5"; // Loose equality (value only) var_dump($num == $str); // Strict equality (value and type) var_dump($num === $str); // Comparing different types var_dump(0 == false); var_dump(0 === false); // Comparing null var_dump(null == ""); var_dump(null === "");
This demonstrates how === is more precise than ==. The strict operator catches type differences that loose equality would ignore through automatic type conversion.
λ php basic_comparison.php bool(true) bool(false) bool(true) bool(false) bool(true) bool(false)
Comparing different types
PHP's type juggling with == can lead to surprising results. The === operator helps avoid these pitfalls by requiring exact type matches.
<?php declare (strict_types=1); // String vs integer var_dump("42" == 42); var_dump("42" === 42); // Empty string vs false var_dump("" == false); var_dump("" === false); // Zero vs false var_dump(0 == false); var_dump(0 === false); // String zero vs false var_dump("0" == false); var_dump("0" === false); // Null vs empty array var_dump(null == []); var_dump(null === []);
These examples show common cases where == might give unexpected true results due to type coercion, while === maintains strict type checking.
λ php type_comparison.php bool(true) bool(false) bool(true) bool(false) bool(true) bool(false) bool(true) bool(false) bool(true) bool(false)
Array comparison
When comparing arrays, === checks that they have the same key/value pairs in the same order and of the same types.
<?php declare (strict_types=1); $arr1 = [1, 2, 3]; $arr2 = ["1", "2", "3"]; $arr3 = [1, 2, 3]; // Loose comparison var_dump($arr1 == $arr2); var_dump($arr1 == $arr3); // Strict comparison var_dump($arr1 === $arr2); var_dump($arr1 === $arr3); // Associative arrays $assoc1 = ["id" => 1, "name" => "Alice"]; $assoc2 = ["id" => "1", "name" => "Alice"]; $assoc3 = ["name" => "Alice", "id" => 1]; var_dump($assoc1 == $assoc2); var_dump($assoc1 === $assoc2); var_dump($assoc1 === $assoc3);
For arrays, === requires identical types for all values, while == will perform type conversion.
// Associative arrays $assoc1 = ["id" => 1, "name" => "Alice"]; $assoc2 = ["id" => "1", "name" => "Alice"]; $assoc3 = ["name" => "Alice", "id" => 1]; var_dump($assoc1 == $assoc2); var_dump($assoc1 === $assoc2); var_dump($assoc1 === $assoc3);
Key order does matter for comparing associative arrays with ===. The
$assoc1
and $assoc3
are not equal even though they
have the same key/value pairs.
λ php array_comparison.php bool(true) bool(true) bool(false) bool(true) bool(true) bool(false) bool(false)
Object comparison
When comparing objects, === checks if both variables reference the exact same instance of an object, not just objects with identical properties.
<?php declare (strict_types=1); class User { public $name; public function __construct($name) { $this->name = $name; } } $user1 = new User("Alice"); $user2 = new User("Alice"); $user3 = $user1; // Loose comparison (checks properties) var_dump($user1 == $user2); var_dump($user1 == $user3); // Strict comparison (checks instance) var_dump($user1 === $user2); var_dump($user1 === $user3); // Checking object IDs var_dump(spl_object_id($user1) === spl_object_id($user3));
The === operator for objects verifies they are the same instance, not just
objects with identical property values. The spl_object_id
function
can help visualize this.
λ php object_comparison.php bool(true) bool(true) bool(false) bool(true) bool(true)
Real-world examples
Using === is particularly important in real-world scenarios like form validation, API responses, and database operations where type safety matters.
<?php declare (strict_types=1); // Form validation $username = $_POST['username'] ?? ''; if ($username === '') { echo "Username is required\n"; } // Database results $user = ['id' => '42', 'active' => '1']; if ($user['active'] === 1) { echo "User is active\n"; } else { echo "User is inactive (strict comparison)\n"; } // API response handling $response = json_decode('{"error": null}', true); if ($response['error'] === null) { echo "No errors\n"; } // Authentication check $token = $_SESSION['token'] ?? null; if ($token === null) { echo "Please login\n"; }
These examples show how === prevents bugs that might occur with == by ensuring exact type matching in critical operations.
λ php practical_usage.php Username is required User is inactive (strict comparison) No errors Please login
Best practices
Following best practices with === helps write more reliable and maintainable PHP code.
<?php declare (strict_types=1); // 1. Default to === unless you specifically need type juggling $input = "0"; if ($input === 0) { // Won't execute, which is usually what you want } // 2. Use === for form validation $age = $_POST['age'] ?? ''; if ($age === '') { echo "Age is required\n"; } // 3. Explicit null checks $value = null; if ($value === null) { echo "Value is null\n"; } // 4. Strict return value checks function findUser($id) { // Returns User object or null return ($id > 0) ? new User() : null; } $user = findUser(0); if ($user === null) { echo "User not found\n"; } // 5. Use === in switch statements switch (true) { case $value === 0: echo "Exactly zero\n"; break; case $value === false: echo "Exactly false\n"; break; } // 6. Document expected types / * @param int|string $id */ function processId($id) { if ($id === 0) { echo "Invalid ID\n"; } }
These practices help avoid common pitfalls and make code behavior more predictable. The key principle is to prefer === unless you have a specific reason to use ==.
Key points to remember:
- Strict equality (===) checks both value and type, while loose equality (==) performs type coercion.
- Use === for form validation, authentication checks, and database operations.
- === is slightly slower than ==, but the performance difference is negligible.
- Default to === unless you specifically need type coercion.
- Helps prevent bugs in edge cases involving 0, "", false, and null.
In this article, we explored the strict equality operator in PHP. We discussed its behavior, compared it with loose equality, and provided real-world examples. We also covered performance considerations and best practices for using === effectively.
Author
List all PHP tutorials.