In PHP (and JavaScript -- which has slightly different behavior), the comparison operator ==
works differently than it does in strongly-typed languages like C or Java. The ===
operator has the behavior that you most likely expect. Below is a breakdown of the two comparison operators as they apply to PHP.
==
This operator is officially known as the "equality" operator, though that doesn't really fit the normal definition of the word "equality". It does what is known as a type-juggling comparison. If the types of both operands don't match (in your example, 1234
was an integer and 1234 test
was a string), PHP will implicitly cast the operands to each others' types and test the equality of the newly-typed values as shown below:
<?php
var_dump( (int) 'hi' ); // int(0)
var_dump( (string) 0 ); //string("0")
var_dump( 'hi' == 0 ); // bool(true)
var_dump( (int) '1hi' ); // int(1)
var_dump( 1 == '1hi' ); // bool(true)
It has a counterpart (type-juggling) inequality operator, !=
.
===
The ===
operator, known as the "identical" operator, performs a strict check of the value and type of both operands and does not perform any implicit casts. Therefore, "0"
does not === 0
and "1234 test"
does not === 1234
.
<?php
var_dump( '1234 test' === 1234 ); // bool(false)
It has a counterpart (strict) inequality operator, !==
.
Quirks
Note that the ===
operator has behavior on objects that is considered strange by some. Say we have class A
and variables $a
and $b
as defined below:
<?php
class A {
public $property = 'default value';
}
$a = new A();
$b = new A();
You might expect var_dump($a === $b);
to output bool(true)
. It will actually return false. When used upon objects, the operator actually checks if both operands are references to the same object. The ==
operator, in this instance, works by checking the properties of the objects, so $a == $b
.
PHP Manual Links
- Comparison operators
- Type juggling