Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not equal to != and !== in PHP

Tags:

operators

php

I've always done this: if ($foo !== $bar)

But I realized that if ($foo != $bar) is correct too.

Double = still works and has always worked for me, but whenever I search PHP operators I find no information on double =, so I assume I've always have done this wrong, but it works anyway. Should I change all my !== to != just for the sake of it?

like image 549
lawrence Avatar asked Sep 04 '10 10:09

lawrence


2 Answers

== and != do not take into account the data type of the variables you compare. So these would all return true:

'0'   == 0
false == 0
NULL  == false

=== and !== do take into account the data type. That means comparing a string to a boolean will never be true because they're of different types for example. These will all return false:

'0'   === 0
false === 0
NULL  === false

You should compare data types for functions that return values that could possibly be of ambiguous truthy/falsy value. A well-known example is strpos():

// This returns 0 because F exists as the first character, but as my above example,
// 0 could mean false, so using == or != would return an incorrect result
var_dump(strpos('Foo', 'F') != false);  // bool(false)
var_dump(strpos('Foo', 'F') !== false); // bool(true), it exists so false isn't returned
like image 63
BoltClock Avatar answered Nov 15 '22 12:11

BoltClock


!== should match the value and data type

!= just match the value ignoring the data type

$num = '1';
$num2 = 1;

$num == $num2; // returns true    
$num === $num2; // returns false because $num is a string and $num2 is an integer
like image 41
Sandeep Avatar answered Nov 15 '22 12:11

Sandeep