PHP Basics : Comparison operators

Understanding what comparison operators are available in PHP code and when to use them for best results.

Tim Wells


PHP comparison operators aren’t that much different from comparison operators in any other language but can be a cause of issues for new users due to the script comparison as well as the difference between equal and identical.

Let’s look at some basic comparison operators.

$a = 10;var_dump($a == 10);
var_dump($a == '10');

The above comparison operators are equal operators. This means it will evaluate the expression, ignoring types for equality. Strings will be converted to integers and vice-versa.

With that understood, the output of this code would be:

bool(true)   // 10 is equal to 10
bool(true) // 10 is equal to '10'

If we wrote those comparisons instead using the identical comparison operator, then it will compare the type.

var_dump($a === 10);
var_dump($a === '10');

As you can see, we’ve used === this time instead of the == from before. This specifies that we want an identical comparison and it will compared the type of the variable. In this case the output is:

bool(true);    // 10 is identical to 10
bool(false); // 10 is not identical to '10'

You might think that the standard equality operator is good, as it will compare a number to a string without a problem. However, it can run into problems.

Let’s compare an integer value to see if it’s true.

$a = 1096;
var_dump($a == true); // bool(true)
var_dump($a === true); // bool(false)

Using equality operators, any number that isn’t 0 will equate to true. Using identical operators it will equate to false. With equality operators, 0 == false, will be true. With identical operators, 0 === false, is false.

$a == $b    // Equal
$a != $b // Not equal
$a === $b // Identical
$a !== $b // Not identical
$a < $b // Less than
$a > $b // Greater than
$a <= $b // Less than or equal to
$a >= $b // Greater than or equal to

Ternary operator



Tim Wells

Self taught software developer and photographer.