PHP Comparison Operators Explained with Examples
What Are PHP Comparison Operators?
In PHP, comparison operators are used to compare two values — numbers, strings, or variables.
These operators return a Boolean result — either true or false — depending on whether the condition is met.
Comparison operators are widely used in if statements, loops, and conditional expressions to make decisions in your code.
Equal Operator (==)
Checks if two values are equal, ignoring data type.
Example:
<?php
$a = 5;
$b = "5";
if ($a == $b) {
echo "Values are equal!";
}
?>
Output:
Values are equal! PHP converts both to the same type before comparison.
Identical Operator (===)
Checks if both value and data type are the same.
Example:
<?php
$a = 5;
$b = "5";
if ($a === $b) {
echo "Values and types are same!";
} else {
echo "Values are equal but types are different!";
}
?>
Output:
Values are equal but types are different!Not Equal Operators (!= or )
Checks if two values are not equal.
Example:
<?php
$x = 10;
$y = 20;
if ($x != $y) {
echo "Values are not equal!";
}
?>
Output:
Values are not equal!Not Identical Operator (!==)
Checks if values or types are not identical.
Example:
<?php
$a = 10;
$b = "10";
if ($a !== $b) {
echo "Values or types are not identical!";
}
?>
Output:
Values or types are not identical!Greater Than Operator (>)
Checks if the left value is greater than the right value.
Example:
<?php
$a = 15;
$b = 10;
if ($a > $b) {
echo "$a is greater than $b";
}
?>
Output:
15 is greater than 10Less Than Operator (<)
Checks if the left value is less than the right value.
Example:
<?php
$a = 5;
$b = 12;
if ($a < $b) {
echo "$a is less than $b";
}
?>
Output:
5 is less than 12Greater Than or Equal To (>=)
Checks if the left value is greater than or equal to the right.
Example:
<?php
$a = 10;
$b = 10;
if ($a >= $b) {
echo "$a is greater than or equal to $b";
}
?>
Output:
10 is greater than or equal to 10Less Than or Equal To (<=)
Checks if the left value is less than or equal to the right.
Example:
<?php
$a = 8;
$b = 10;
if ($a <= $b) {
echo "$a is less than or equal to $b";
}
?>
Output:
8 is less than or equal to 10Spaceship Operator ()
Introduced in PHP 7, the spaceship operator compares two values and returns:
0if both are equal1if the left is greater-1if the right is greater
Example:
<?php
echo 10 <=> 10; // 0
echo "<br>";
echo 20 <=> 10; // 1
echo "<br>";
echo 5 <=> 15; // -1
?>
Output:
0 1 -1Real-World Example: Comparing Student Scores
<?php
$marks = 75;
if ($marks >= 90) {
echo "Grade: A+";
} elseif ($marks >= 75) {
echo "Grade: A";
} elseif ($marks >= 50) {
echo "Grade: B";
} else {
echo "Fail";
}
?>
Output:
Grade: A