Categories
comparison operators php

The 3 different equals

159

What is the difference between =, ==, and ===?

I think using one equal sign is to declare a variable while two equal signs are for a comparison condition and lastly three equal signs are for comparing values of declared variables.

5

  • check out the example … I have posted it would clarify more things ..

    Jan 14, 2010 at 10:55

  • 1

    For advanced PHP users, knowing the difference between == and === and asking themself “is it faster to compare with == or with === when I’m sure that both the operands are the same type?”, please look at my benchmark script below.

    Jul 8, 2013 at 14:04

  • @Strawberry I feel the question’s tag should also include the javascript tag since it also applies to that language.

    Jun 11, 2016 at 18:35


  • (Update): I have added the javascript tag in an edit, since there have been quite a few questions where people were using = in javascript. That doesn’t only apply to PHP but other languages also.

    Jun 11, 2016 at 19:09

  • I went ahead and deleted the JavaScript tag: all answers here are only about PHP (except the latest which is very weak), there are differences between how the languages handle it, and there is already a similar de facto canonical JavaScript question (Which equals operator (== vs ===) should be used in JavaScript comparisons?).

    – JJJ

    May 16, 2018 at 10:34

179

You have = the assignment operator, == the ‘equal’ comparison operator and === the ‘identical’ comparison operator.

$a = $b     Assign      Sets $a to be equal to $b.
$a == $b    Equal       TRUE if $a is equal to $b.
$a === $b   Identical   TRUE if $a is equal to $b, and they are of the same type. (introduced in PHP 4)

For more info on the need for == and ===, and situations to use each, look at the docs.

3

  • when I compare two identical datetime, I have false result, why ? example : sandbox.onlinephpfunctions.com/code/…

    – stloc

    Jan 8, 2016 at 9:20

  • 4

    @stloc, === with objects tells you if they are the same object, not if they have the same content.

    – Andrea

    Jan 27, 2016 at 20:22

  • Introduced in PHP4, funny in Y2018 😉

    – mvorisek

    Jul 13, 2018 at 15:36

23

  • = is the assignment operator
  • ==
    is the comparison operator (checks if
    two variables have equal values)
  • === is the identical comparison
    operator (checks if two variables
    have equal values and are of the same
    type).

    9

    = assignment operator

    == checks if two variables have the same value

    === checks if two variables have the same value AND if their types are the same

    1

    • 1

      Also know about != and !== ‘not’ versions of the two comparison operators. Some languages use := as assignment, just to avoid this kind of confusion.

      Aug 21, 2013 at 16:57