PHP

🔍 Comparison Operators in PHP

Comparison Operators in PHP are used to compare two values. Evaluating a comparison always yields a boolean result: either true (condition holds) or false (condition fails). These operators form the backbone of conditional execution statements such as if, else, and control loops.

  • Best Practice: Always prefer identity operators (=== and !==) over loose equality operators (== and !=) to prevent silent bugs caused by PHP's dynamic type coercion.

🛠️ Comparison Operators and Code Examples

1️⃣ Loose Equality (==) vs. Strict Identity (===)
Loose equality compares only values with type coercion, whereas identity checks both value and data type strictly:

PHP
// Loose Equality (==) - Type coercion allowed
var_dump("8" == 8);  // Outputs: bool(true)

// Strict Identity (===) - Values AND types must match
var_dump(8 === 8);   // Outputs: bool(true)
var_dump("8" === 8); // Outputs: bool(false)

2️⃣ Inequality (!= / <>) vs. Strict Inequality (!==)
Tests whether values or types differ from one another:

PHP
// Loose Inequality (!= or <>)
var_dump(8 != 8);    // Outputs: bool(false)
var_dump("8" != 8);  // Outputs: bool(false)

// Strict Inequality (!==) - Returns true if value OR type is different
var_dump("8" !== 8); // Outputs: bool(true)

3️⃣ Relational Operators (<, >, <=, >=)
Evaluates relative numeric size or alphabetical precedence:

PHP
// Less than (<) and Greater than (>)
var_dump(5 < 8);  // Outputs: bool(true)
var_dump(5 > 3);  // Outputs: bool(true)

// Less than or equal to (<=)
var_dump(5 <= 8); // Outputs: bool(true)
var_dump(5 <= 5); // Outputs: bool(true)

// Greater than or equal to (>=)
var_dump(5 >= 3); // Outputs: bool(true)
var_dump(5 >= 8); // Outputs: bool(false)

📊 Comparison Operators Quick Reference

Operator Name Example Description
== Equal $a == $b True if $a is equal to $b after type coercion.
=== Identical $a === $b True if $a is equal to $b, and they are of the same type.
!= / <> Not Equal $a != $b True if $a is not equal to $b after type coercion.
!== Not Identical $a !== $b True if $a is not equal to $b, or they are not of the same type.
< Less Than $a < $b True if $a is strictly less than $b.
> Greater Than $a > $b True if $a is strictly greater than $b.
<= Less Than or Equal To $a <= $b True if $a is less than or equal to $b.
>= Greater Than or Equal To $a >= $b True if $a is greater than or equal to $b.
  • 📝 Short Summary

  • Comparison operators always evaluate to a boolean true or false.
  • Use === and !== in production to ensure both value and type match expected parameters safely.
  • Relational operators (<, >, <=, >=) operate on numbers as well as string sorting order.