Double and Triple equals operator in PHP

  • A double = sign is a comparison and tests whether the variable / expression / constant to the left has the same value as the variable / expression / constant to the right.
  • A triple = sign is a comparison to see whether two variables / expressions / constants are equal AND have the same type – i.e. both are strings or both are integers.

In simplest terms:

PHP code
== checks if equivalent (value only)

=== checks if the same (value && type)

In PHP:

true == 1 (true – equivalent in value)

true === 1 (false – not the same in value && type)

true is boolean

1 is int

Here’s a table we put together showing how some variables compare to each other.

// “===” means that they are identical

// “==” means that they are equal

// “!=” means that they aren’t equal.

[ad type=”banner”]

Difference between == and ===

Comparison Operators:-

Loosely == equal comparison:

  • If you are using the == operator, or any other comparison operator which uses loosely comparison such as !=, <> or ==, you always have to look at the context to see what, where and why something gets converted to understand what is going on.

Strict === identical comparison:

  • If you are using the === operator, or any other comparison operator which uses strict comparison such as !== or ===, then you can always be sure that the types won’t magically change, because there will be no converting going on.
  • So with strict comparison the type and value have to be the same, not only the value.

Example:

php code
1 === 1: true
1 == 1: true
1 === "1": false // 1 is an integer, "1" is a string
1 == "1": true // "1" gets casted to an integer, which is 1
"foo" === "foo": true // both operands are strings and have the same value

Warning: two instances of the same class with equivalent members do NOT match the === operator. Example:

javascript code
$a = new stdClass();
$a->foo = "bar";
$b = clone $a;
var_dump($a === $b); // bool(false

When should we use == and when ===? Here’s an example.

If we write

if ($_REQUEST[name] == “”) …..

then  testing to see if a name has been entered on a form – it will return true if no name has been entered and it will also return true if there wasn’t an input box on the form called “name” or if the URL was called up without a form at all. However, if we use the three-equals varient:

if ($_REQUEST[name] === “”) …..

then this will return true if and only if the form had an input box called “name” into which the user didn’t type anything at all.

  • Naturally, there will be times when you want to check very specifically that the form was submitted but with an empty box, and other times where you want to check simply if you’ve got a name or not (for whatever reason).
  • That’s why PHP has the flexibility and provides both == and ===
[ad type=”banner”]

Categorized in: