PHP switch statement loose comparison


This article goes over a gotcha of PHP switch statements.

Quiz

Question 1

What does the following output?

switch (null) {
  case '':
    var_dump('');
    break;
  case null:
    var_dump(null);
    break;
}

The answer is string(0) "".

Question 2

What does the following output?

switch ('') {
  case null:
    var_dump(null);
    break;
  case '':
    var_dump('');
    break;
}

The answer is NULL.

Question 3

What does the following output?

switch ('0') {
  case 0:
    var_dump(0);
    break;
  case '0':
    var_dump('0');
    break;
}

The answer is int(0).

Loose comparison

Because PHP switch/case does loose comparison, it can evaluate incorrectly for the cases:

  • true
  • false
  • 1
  • 0
  • -1
  • '1'
  • '0'
  • '-1'
  • null
  • []
  • ''

This is due to PHP’s implicit casting or type juggling.

See Repl.it:



Please support this site and join our Discord!