views:

675

answers:

4

I keep seeing variations of this:

Not equal !=

Not equal, equal

!==

Which one is the standard or do they have different meanings?

I am guessing the latter also checks the value and the name if it's a string, while the former might just check the value only...

+2  A: 

!= not equal by value

!== not equal by value and type

Svetlozar Angelov
+10  A: 

== and != check equality by value, and in PHP you can compare different types in which certain values are said to be equivalent.

For example, "" == 0 evaluates to true, even though one is a string and the other an integer.

=== and !== check the type as well as the value.

So, "" === 0 will evaluate to false.


Edit: To add another example of how this "type-juggling" may catch you out, try this:

var_dump("123abc" == 123);

Gives bool(true)!

Ben James
Thank you guys, for the fast response, so using !== or just == adds a check for the type as well as the value, thank you.
Newb
PHP allows values to be freely converted from one type to another. If you convert a string "456" to a number, it will be converted to 456. Very convenient. The PHP comparison operator == only checks value. So, `"456"==456`. Now, "" (empty string) would be equal to 0, and to FALSE, and to NULL. But sometimes you don't want this. To check whether something is FALSE instead of just 0, you can use `var === FALSE`
nash
Comparison operator, only checks values (==), thanks
Newb
To compare for value and type you use either !== or ===. Not ==
Htbaa
+2  A: 

The second one is type-strict.

"1" != 1;  // false
"1" !== 1; // true because the first is a string, the second is a number
Andy E
+1  A: 

in an example:

"2" == 2 -> true

"2" === 2 -> false

"2" !== 2 -> true

"2" != 2 -> false

this is also important when you use certain function that can return 0 or false

for example strpos: you want always to check types too there, not only values. because 0 == false but 0 !== false.

since strpos can return 0 if a string is at the first position. but that not the same as false, which means the string has not been found.

kon
"2" is a string, so when using == we are doing both checks for type and value so the result is true for the first case.However, for the second case the === makes it stricter (type and value must match); therefore, we find that the string "2" is not going to be equal to the value 2, interesting.
Newb
Just got enlightened by Ben James, == only checks for values.
Newb