-2

Often, I see in if statements for php something like this:

if (null === $variable) {
    // do stuff
}

What does it do and what is it for?

EDIT: I totally get that it is a comparison operator, I just wonder why not $variable === null.

Dima Dz
  • 492
  • 5
  • 16

2 Answers2

3

It's not an assignment, it's a comparison for equality. It determines if the variable $variable contains the value null.

More in the documentation:

why not to check $variable === null

Some people like to use the form with the constant on the left (a "Yoda condition", it is called) so that if they have a typo and only type a single =, it causes a syntax error rather than doing an assignment.

T.J. Crowder
  • 959,406
  • 173
  • 1,780
  • 1,769
1

That is the Yoda style usually used as a trick by programmers to prevent accidental assignments which always give some silent bugs.

Example:

  var a = dosomething();

  if(a = null){
      //more here
   }

Note that the if block will always not execute regardless of the result of doSomething method since we assign then check for equality. This assignment nullifies the possibly non-deterministic nature of doSomething

Peter Chaula
  • 3,094
  • 2
  • 22
  • 29