Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does === do in PHP

I have been programming in PHP for a while but I still dont understand the difference between == and ===. I know that = is assignment. And == is equals to. So what is the purpose of ===?

like image 950
Josh Curren Avatar asked May 14 '09 20:05

Josh Curren


2 Answers

It compares both value and type equality.

 if("45" === 45) //false
 if(45 === 45) //true
 if(0 === false)//false

It has an analog: !== which compares type and value inequality

 if("45" !== 45) //true
 if(45 !== 45) //false
 if(0 !== false)//true

It's especially useful for functions like strpos - which can return 0 validly.

 strpos("hello world", "hello") //0 is the position of "hello"

 //now you try and test if "hello" is in the string...

 if(strpos("hello world", "hello")) 
 //evaluates to false, even though hello is in the string

 if(strpos("hello world", "hello") !== false) 
 //correctly evaluates to true: 0 is not value- and type-equal to false

Here's a good wikipedia table listing other languages that have an analogy to triple-equals.

like image 132
Tom Ritter Avatar answered Oct 03 '22 11:10

Tom Ritter


It is true that === compares both value and type, but there is one case which hasn't been mentioned yet and that is when you compare objects with == and ===.

Given the following code:

class TestClass {
  public $value;

  public function __construct($value) {
    $this->value = $value;
  }
}

$a = new TestClass("a");
$b = new TestClass("a");

var_dump($a == $b);  // true
var_dump($a === $b); // false

In case of objects === compares reference, not type and value (as $a and $b are of both equal type and value).

like image 37
Thorbjørn Hermansen Avatar answered Oct 03 '22 11:10

Thorbjørn Hermansen