12

Is there a difference between !== and != in PHP?

Daryl Gill
  • 5,464
  • 9
  • 36
  • 69
barfoon
  • 27,481
  • 26
  • 92
  • 138
  • 6
    Very commonly duplicated question, depending on how you search for the answer: http://stackoverflow.com/questions/80646/how-do-the-equality-and-identity-comparison-operators-differ – spoulson Jul 16 '09 at 17:49

7 Answers7

34

The != operator compares value, while the !== operator compares type as well.

That means this:

var_dump(5!="5"); // bool(false)
var_dump(5!=="5"); // bool(true), because "5" and 5 are of different types
Ben Blank
  • 54,908
  • 28
  • 127
  • 156
Salty
  • 6,688
  • 3
  • 33
  • 31
  • null!="null" is not false, wrong example. Also echo prints 1 for bool(true) and nothing for bool(false). The actual output of the code snippet is 11. – VolkerK Jul 16 '09 at 18:01
  • @VolkerK — I don't have a PHP interpreter in front of me, but hopefully this is a more accurate example. :-) – Ben Blank Jul 16 '09 at 18:31
  • My mistake. Thanks for the edit, Ben Blank. Hopefully the original poster didn't get confused. – Salty Jul 16 '09 at 18:40
  • `==` also treats type a little differently from `===` - for instance, numeric strings ("5", "05") are compared as numbers, and associative arrays in different orders can still be equal. I would describe `===` as "exactly the same", rather than "equal value and type". – Brilliand Mar 26 '14 at 16:06
8

!= is the inverse of the == operator, which checks equality across types

!== is the inverse of the === operator, which checks equality only for things of the same type.

Welbog
  • 59,154
  • 9
  • 110
  • 123
4

!= is for "not equal", while !== is for "not identical". For example:

'1' != 1   # evaluates to false, because '1' equals 1
'1' !== 1  # evaluates to true, because '1' is of a different type than 1
Kevin Lacquement
  • 5,057
  • 3
  • 25
  • 30
3

!== checks type as well as value, != only checks value

$num =  5

if ($num == "5") // true, since both contain 5
if ($num === "5") // false, since "5" is not the same type as 5, (string vs int)
Ian Elliott
  • 7,588
  • 5
  • 35
  • 42
2

=== is called the Identity Operator. And is discussed in length in other question's responses.

Others' responses here are also correct.

Matthew Vines
  • 27,253
  • 7
  • 76
  • 97
2

Operator != returns true, if its two operands have different values.

Operator !== returns true, if its two operands have different values or they are of different types.

cheers

Arnkrishn
  • 29,828
  • 40
  • 114
  • 128
1

See the PHP type comparison tables on what values are equal (==) and what identical (===).

Gumbo
  • 643,351
  • 109
  • 780
  • 844