Logo
Since 1998

In PHP, the switch statement manages a string and case 0 quite unorthodoxically

I bumped into a wicked behaviour of the switch statement in PHP; it considers that any string equals 0 if the integer case 0 is encountered first.
Everybody knows the following construct:
<?php

...

switch(
$variable) {
  case 
'value1':
    
// Business 1
  
break;

  case 
'value2':
    
// Business 2
  
break;

  default:
    
// Default business
}
Obviously one can replace strings value1 and value2 with constants: CASE1 et CASE2.

Example :
<?php

...

define('CASE1''value1');
define('CASE2''value2');

switch(
$variable) {
  case 
CASE1:
    
// Business 1
  
break;

  case 
CASE2:
    
// Business 2
  
break;

  default:
    
// Default business
}
So far you must still be with me.  But were you will stop to be is in the case where a constant used behind a case statement equals integer 0 while the variable checked against in the switch brackets is a string.  In this case, it is case 0 that supersedes is encountered first, such as in the example below:


<?php
define
('CASE1'0);
define('CASE2''foobar');

// index.php?parametre=foobar
$variable $_GET['parametre'];

switch(
$variable) {
  case 
CASE1:
    
// I always supersede
  
break;

  case 
CASE2:
    
// Business 2
  
break;

  default:
    
// Default business
}
But not in the next example, because it is not encountered first:


<?php
define
('CAS1'0);
define('CAS2''foobar');

// index.php?parametre=foobar
$variable $_GET['parametre'];

switch(
$variable) {

  case 
CAS2:
    
// I supersede
  
break;

  case 
CAS1:
    
// I can't win because I come after a better match
  
break;

  default:
    
// Default business
}
Unbelievable! switch acts as if variable $variable equalled 0 regardless of its actual value.  It is an awkward situation of a degraded“case” . . .   So keep in mind this strange and somewhat dodgy behaviour next time you code a switch statement.
(480 views)
created 05 November 2013
revised 26 February 2017 by
Would you accept our confidentiality policy? It is about cookies and personal data...