PHP - Operator Comparison Operators

Introduction

Comparison operators compares one operand with the other in various ways.

If the comparison test is successful, the expression evaluates to true; otherwise, it evaluates to false.

You can use comparison operators with decision and looping statements such as if and while.

Here's a list of the comparison operators in PHP:

OperatorNameExample Result
== equal $x == $y true if $x equals $y ; false otherwise
!= or <> not equal$x != $y true if $x does not equal $y ; false otherwise
===identical $x === $y true if $x equals $y and they are of the same type;false otherwise
!== not identical $x !== $y true if $x does not equal $y or they are not of the same type; false otherwise
<less than $x < $y true if $x is less than $y ; false otherwise
>greater than $x > $ytrue if $x is greater than $y ; false otherwise
<= less than or equal to $x <= $y true if $x is less than or equal to $y ; false otherwise
>= greater than or equal to $x >= $ytrue if $x is greater than or equal to $y ; false otherwise

The following examples show comparison operators in action:

Demo

<?php

$x = 23;//from ww  w.  ja v a 2s.com
echo ( $x  <  24 ) . " \n ";     // Displays 1 (true)
echo ( $x  <  "24 "  ) . " \n ";   // Displays 1 (true) because

// PHP converts the string to an integer
echo ( $x == 23 ) . " \n ";    // Displays 1 (true)
echo ( $x === 23 ) . " \n ";   // Displays 1 (true)
echo ( $x === "23 "  ) . " \n "; // Displays "" (false) because

// $x and "23" are not the same data type
echo ( $x  >= 23 ) . " \n ";    // Displays 1 (true)
echo ( $x  >= 24 ) . " \n ";    // Displays "" (false)
?>

Result

Comparison operators are commonly used to compare two numbers or strings converted to numbers.

The == operator is used to check that two strings are the same.

Related Topics