Friday, June 5, 2009

the "==" and the "===" operators

PHP has two types of comparison operators: "==" and "===" ( and respectively "!=" and "!==" ).

Variables

"==" offers a simple comparison of the content of variables, skipping the type (int, string, boolean,...) of the variables.
The following expression are equivalent to the operator "==":
  • false
  • 0
  • ""
  • ''
  • "0"
  • 0.0
  • -0
  • !1
  • array()
  • $i // where $i is not initialized (notice generated)
  • strpos("abcd","a") // (*)
The following expression are the same for the operator "==", as well
  • true
  • 1
  • "a"
  • 0.1
  • -1
  • array(1)
  • !0
  • " " //space
Differently, for the "===" operator, the two expression are equal ONLY IF the contents and THE TYPES are the same. The items in both list are different for the operator "===".
Note also these other cases:
  • 0===0.0 //int and double : false !
  • 1.5===1+0.5 //true ! 1 promoted to double 1.0
  • $i =0; $i===0 //true
  • $j===$m //true. ($j and $m are not initialized, notice generated)
(*) strpos($str, $search) [manual] returns the position of $search in the string $str, or returns "false" if not. This function is common used to control the existence of a string in another string. To do it, remember to use the operator "!==" !! If the $search is in position 0, the function returns 0 (and 0==false) !! In php code:

print strpos("abcd","a")?"exists":"not exists"; //not exists -> SEMANTIC ERROR !!!
print strpos("abcd","a")!=false?"exists":"not exists"; //not exists -> SEMANTIC ERROR !!!
print strpos("abcd","a")!==false?"exists":"not exists"; // exists -> CORRECT !


objects
Similarly, for the "==" operator, two objects are equal if they are instantiated from the SAME class and the comparison of their elements (using "==" operator, not "===") is true

class A
{
private $v;
pub
lic function __construct($v) { $this->v = $v; }
}

Now, read carefully the following line. Two object of the same class are equal for the operator "=="
new A( array(true,1.0) ) == new A(array(1,1)) // true !!
new A( array() ) == new A(array(1,2,3)) // true !!

Differently, for the "===" operator, the two object equal ONLY IF they refer to the SAME OBJECT!!

new A( 1 ) === new A(1); //false
$a = new A( 1 );
$aCopy = $a;
$aClone = clone $a;
$a === $aCopy; // true ! the two references point to the same object !
$a === $aClone; //false ! a clone is a different object !



No comments:

Post a Comment

 

PHP and tips|PHP