SSISO Community

시소당

제어구조 - switch

switch구문은  연속적인  같은  표현식을  갖는  연속적인  IF구문과  비슷하다.  많은  경우,  하나의  변수(또는  표현식)으로  다른  많은  값과  비교할  필요가  있으며,  그  값이  동일한  코드의  파편들을  수행할  필요가  생기게  된다.  정확히  이런  목적을  위해  switch구문이  사용된다.  

참고:  다른  언어와는  달리  continue문은  switch문에서  사용할수  있고,  break문과  비슷하게  동작한다.  루프  내에  switch문을  포함하고  있고  바깥  루프의  다음  반복문으로  진행하고  싶다면  continue  2를  사용한다.  

다음  예제  코드들은  같은  일을  서로  다르게  표현한  것입니다.  하나는  if와  elseif문을  사용한  것이고,  다른  하나는  switch문을  사용했습니다:  


<?php
if  ($i  ==  0)  {
      echo  "i는  0";
}  elseif  ($i  ==  1)  {
      echo  "i는  1";
}  elseif  ($i  ==  2)  {
      echo  "i는  2";
}

switch  ($i)  {
case  0:
      echo  "i는  0";
      break;
case  1:
      echo  "i는  1";
      break;
case  2:
      echo  "i는  2";
      break;
}
?>    



실수하지  않기  위해  switch문이  어떻게  동작하는지  이해할  필요가  있다.  switch문은  한줄씩  수행된다  (실제는,  한구문씩).  처음에는  아무  코드도  수행되지  않는다.  오직  값을  갖는  case문이  발견될때에만  구문을  수행하기  시작한다.  PHP는  switch블록의  끝부분이  될때까지,  또는  break문와  첫번째  조우를  할때까지  구문을  계속  수행해  간다.  만약  각  case  구문  목록의  끝부분에  break문을  쓰지않는다면  PHP는  다음  case문으로  계속  진행하게  된다.  예를  들면  다음과  같다:  


<?php
switch  ($i)  {
case  0:
      echo  "i는  0과  같다";
case  1:
      echo  "i는  1과  같다";
case  2:
      echo  "i는  2와  같다";
}
?>    



여기에서,  $i가  0이라면  PHP는  모든  echo문을  수행합니다!  $i가  1이면  밑의  두  echo문을  수행합니다.  $i가  2일때만  원하는  동작  ('i는  2와  같다'를  표시)을  합니다.  따라서  break문을  잊어서는  안됩니다.  (어떤  경우에는  일부러  빠뜨릴수  있을지  모르지만)  

switch구문에서,  조건문은  오직  한번만  평가되고  각  case문에서  결과가  비교되어진다.  elseif문에서는  조건문은  다시  평가된다.  조건문이  한번  이상의  비교가  필요한  복잡한  것이거나  거친(tight)  루프안에  있다면  switch문  좀  더  빠를것이다.  

case에  대한  구문  목록은  비어있을수  있다.  이것은  단순히  다음  case문으로  제어권을  넘겨줄  뿐이다.  


<?php
switch  ($i)  {
case  0:
case  1:
case  2:
      echo  "i는  3보다  작지만  음수는  아닙니다.";
      break;
case  3:
      echo  "i는  3";
}
?>    



특별한  case가  바로  default  case문이다.  이것은  다른  case문과  모두  조건이  맞지  않을때의  경우를  위한것이고,  case구문의  마지막에  위치해야  한다.  예제  코드는  다음과  같다:  


<?php
switch  ($i)  {
case  0:
      echo  "i는  0과  같다";
      break;
case  1:
      echo  "i는  1과  같다";
      break;
case  2:
      echo  "i는  2와  같다";
      break;
default:
      echo  "i는  0,  1,  2  어느것도  아니다";
}
?>    



case의  표현식은  정수나  부동소수점  수와  문자열같은  단순형으로  평가되는  어던  표현식도  될수  있다.  여기에  단순형으로  재참조(dereference)되지  않는  배열이나  객체를  사용할수는  없다.  

switch문을  위한  제어  구조의  대체  문법이  지원된다.  더  자세한  정보는  제어  구조의  대체  문법을  참고.  


<?php
switch  ($i):
case  0:
      echo  "i  equals  0";
      break;
case  1:
      echo  "i  equals  1";
      break;
case  2:
      echo  "i  equals  2";
      break;
default:
      echo  "i  is  not  equal  to  0,  1  or  2";
endswitch;
?>    






  add  a  note  User  Contributed  Notes
switch  
jonybd  at  yahoo  dot  com
28-Jun-2005  09:25  
/*
      Have  one  value  need  to  deal  with  currency
      -  follow  as  example
*/
while  ($row  =  mysql_fetch_array($v_Result,MYSQL_NUM))  {
      $v_BAL  =  $row[1]/10000;
      
      switch  (TRUE){

              case  ($v_BAL  <=  0):                        //less  then  0  ,  -0  
                      echo  $v_BAL;
              break;
                                      
              case  ($v_BAL  <=  10  AND  $v_BAL  >=  1):        //less  then  10  and  greater  then  1
                      echo  $v_BAL;
              break;
                                                                              
              default:                                //default
                      echo  $v_BAL;
              break;
      }
}  
Bob
24-Jun-2005  12:29  
//  The  code  posted  on    10-Jun-2005  01:40  has  an  error
//  The  switch  condition  should  test  against  TRUE  not  $month_name

$month_name  =  'Jan';

switch  (  TRUE)  {
      case  ($month_name  ===  "Jan"  ||  $month_name  ===  "January"):
              $month_num  =  "1";
      break;
      default:
              $month_num  =  "???";    
      break;
}
  
  echo  $month_num;  
grins1  at  hotmail  dot  com
11-Jun-2005  02:40  
Just  so  its  out  here  for  all  to  see,  a  way  to  check  for  multiple  conditions  per  case  using  the  example  from  04-Jun-2005  03:24:

switch  ($month_name)  {
      case  ($month_name  ===  "Jan"  ||  $month_name  ===  "January"):
              $month  =  "1";
      break;
}

With  or  without  the  parenthesis  is  fine.

I  wasn't  sure  until  I  went  through  the  motions  and  played  around  with  it.  
09-Jun-2005  12:55  
regarding  the  previous  comment:  ("Jan"  ||  "January")  is  an  expression  which  will  evaluate  to  true;  it  is  not  valid  syntax  for  multiple  cases  in  a  switch  statement.  
dohpaz  at  kennethpaul  dot  com
05-Jun-2005  07:24  
I  haven't  seen  anything  specifically  pointing  this  out,  but  you  can  get  a  small  performance  increase  in  your  code  by  re-structuring  your  complex  switch  statements.

For  example,  I  was  using  the  following  switch  to  convert  textual  month  names  into  their  numerical  counterparts  from  the  Date  header  of  email  on  my  pop  server:

switch  ($month_name)  {
    case  "Jan":
    case  "January":
      $month  =  "1";
      break;
    ...
}

Even  just  looping  through  15  emails  on  the  server,  it  would  take  upwards  of  around  9-10  seconds!  So,  I  decided  to  shorten  my  switch  statement  to  something  like  this:

switch  ($month_name)  {
    case  ("Jan"  ||  "January"):  $month  =  "1";  break;
    ...
}

Doing  this  I  actually  shaved  3  seconds  from  my  script's  execution  time!!!  I  thuoght  this  was  well  worth  noting  for  other  coders  out  there  who  are  looking  to  optimize  their  PHP  code.  
ant  at  loadtrax  dot  com
25-Mar-2005  02:01  
This  caught  me  out.  The  number  '6'  when  compared  with  the  string  '6b'  returns  true.  The  solution  is  to  either  typecast  the  compare    -    ie,  "  switch  ((string)$type):  "    or  to  make  sure  $type  is  a  string  (eg  $type="6")

<?
$type=6;
switch  ($type):
      case  "6b":
              print  "6b:  ";
              print  $type;
      break;
      case  "6":
              print  "6:  ";
              print  $type;
      break;
endswitch;
?>  
Bruno  Feu
23-Mar-2005  06:22  
You  can  solve  the  problem  by  just  writing  the  following  piece  of  code:

<?php
$x  =  18;
$y  =  6;

switch  ($x)  {
      case  ($y  *  4):
      case  (9  *  3):
              echo  "Member";
              break;
      default:
              echo  "Not  a  member";
}
?>  
ach  aat  bitfabrik  doot  de
14-Mar-2005  08:21  
So  instead  of  writing  the  code  shown  below  it  would  have  to  be  like  this:

<?php
$x  =  18;
$y  =  6;

switch  ($x)  {
      case  ((($y  *  4)  ||  (9  *  3))?$x:false):
              echo  "Member";
              break;
      default:
              echo  "Not  a  member";
}
?>

So  now  the  case  expression  contains  an  if  statement  in  simplified  notation  which  either  returns  the  value  of  $x  if  the  expression  is  true  (so  the  case  matches)  or  false,  if  the  expression  was  false  (so  the  case  does  not  match).
Be  aware  that  it  only  works  if  $x  never  actually  is  "false"  because  then  it  would  match  in  either  case.  So  the  "false"  in  the  above  code  should  always  be  any  random  value  which  is  not  a  possible  value  for  $x.  
gregory  dot  mccoy  at  pleasedontspam  dot  cafeoui  dot  net
14-Mar-2005  02:07  
In  the  post:
----------------------------------------------------
design  at  hyperoptix  dot  com
18-Feb-2004  12:46
Boolean  logic  does  not  work  inside  case  statements:

<?php
$x  =  18;
$y  =  6;

switch  ($x)  {
      case  (($y  *  4)  ||  (9  *  3)):
              echo  "Member";
              break;
      default:
              echo  "Not  a  member";
}
?>

echoes  "Member".
----------------------------------------------------
there  were  many  responses  but  all  seem  to  miss  the  point.    You  cannot  mix  apples  and  oranges.    The  "switch($x)"  establishes  that  this  "switch"  statement  will  be  a  Relational  syntax  while  the  "case"  qualifier  uses  a  Logical  syntax.    There  must  be  a  match.    Either  change  "switch($x)"  to  "switch(true)"  or  change  "case(($y  *  4)  ||  (9  *  3)):"  to  resolve  to  a  value.

The  syntax  of  the  original  post  is  like  a  cop  that  says,  "I  want  all  of  your  answers  to  reflect  truth.    So,  are  you  eighteen?"    The  respondent  says,  "  4  x  4  or  11  +  5".    Need  I  say  more?  
rdoggett  at  oz  dot  net
19-Jan-2005  10:01  
Here's  an  often  overlooked  way  of  doing  (nearly)  the  same  thing:
<?php
echo  ($i  ==  0)  ?    "i  is  zero"  :
          (($i  ==  1)  ?    "i  equals  1"  :
          (($i  ==  2)  ?    "i  equals  2"  :  ""));
?>
This  may  be  an  idiomatic  surprise  at  first.    But  the  clean  and  concise  code  speaks  for  itself.

Beware;  PHP  seems  to  parse  the  ternary  operator  with  a  different  precedence  than  other  languages  such  as  C  or  perl  or  javascript.    This  means  PHP  requires  nested  parenthesis  around  each  nested  group  to  avoid  unexpected  results.    Even  so,  this  construct  is  still  very  understandable  and  maintainable,  compared  to  the  equivalent  switch  or  if  statements.  
Derek  Ethier
23-Dec-2004  04:43  
A  word  of  caution  around  the  order  used  for  the  case/default  controls.    I  notice  that  a  lot  of  people  do  not  break;  the  default  section  and  the  following  could  lead  to  incorrect  results  when  run.

$a  =  "lowercase";

switch  (  $a  )  {
    default:
      $a  =  strtoupper(  $a  );
      print  $a  .  "<br  />";

    case  (  'LOWERCASE'  ):
      print  $a  .  "<br  />";
      break;
}

Result:
LOWERCASE
LOWERCASE

Placing  a  break;  in  the  default  control  will  result  in:
LOWERCASE

..  as  expected.    Also,  placing  the  default  section  at  the  bottom  (as  in  an  else  control)  will  also  display  the  correct  result.  
Bachsau
20-Dec-2004  09:52  
Be  carefull:  If  you  want  to  test  the  return  of  a  function,  you  have  to  use  switch,  because  if  you  use  'if'  and  'ifelse',  your  function  will  be  executed  every  time  again.

For  example  if  use  use  the  following  construct:

if(file_get_contents('file.htm',  0)  ==  'typ1')  {
          //  Do  one  thing
}
ifelse(file_get_contents('file.htm',  0)  ==  'typ2')  {
          //  Do  the  second  thing
}
ifelse(file_get_contents('file.htm',  0)  ==  'typ3')  {
          //  Do  the  third  thing
}

The  file  will  be  requested  3  times!!!

If  you  use  the  following:

switch  (file_get_contents('file.htm',  0))  {
          case  'typ1':  //  Do  one  thing
          break;
          case  'typ2':  //  Do  the  second  thing
          break;
          case  'typ3':  //  Do  the  third  thing
}

The  file  will  be  requested  only  once!!!  
pentek_imre  at  mailbox  dot  hu
23-Oct-2004  08:25  
Using  select  is  like  using  ==  (instead  of  ===)  in  an  if  statement.  Let's  see  an  example:
<?php
function  Describe($Q)
{
    var_dump($Q);
    echo  ":  ";
    switch  ($Q)
      {
      case  "0":
          echo  "String  zero";
          break;
      case  0:
          echo  "Integer  zero";
          break;
      case  NULL:
          echo  "NULL  NULL";
          break;
      case  FALSE:
          echo  "Boolean  FALSE";
          break;
      case  "":
          echo  "Empty  string";
          break;
      default:
          echo  "Any  other  value";
          break;
      }
    echo  "<BR>\n";
}
Describe("0");
Describe(0);
Describe(NULL);
Describe(FALSE);
Describe("");
Describe(1);
?>
Output  (PHP  5.0.1)  is:
string(1)  "0"  :  String  zero
int(0)  :  String  zero
NULL  :  Integer  zero
bool(false)  :  String  zero
string(0)  ""  :  Integer  zero
int(1)  :  Any  other  value  
tom  AT  csbanana  DOT  com
12-Oct-2004  02:18  
If  you're  using  switch()  inside  a  function  and  you're  returning  a  $var  inside  each  case,  you  won't  need  to  include  break()  as  return()  will  end  the  execution  of  the  switch  and  function.  
manicdepressive  at  mindless  dot  com
22-Apr-2004  08:43  
Be  careful  if  distinguishing  between  NULL  and  (int)0.    As  implied  in  the  above  documentation,  the  case  statements  are  equivalent  to  the  '=='  operator,  not  the  '==='  operator,  so  the  following  code  did  not  work  as  i  expected:

<?php
$mixed  =  0;
switch($mixed){
      case  NULL:  echo  "NULL";    break;
      case  0:  echo  "zero";    break;
      default:  echo  "other";  break;
}
?>

Instead,  I  may  use  a  chain  of  else-ifs.    (On  this  page,  kriek  at  jonkreik  dot  com  states  that  "in  most  cases  [a  switch  statement]  is  15%  faster  [than  an  else-if  chain]"  but  jemore  at  m6net  dotdot  fr  claims  that  when  using  ===,  if/elseif/elseif  can  be  2  times  faster  than  a  switch().)

Alternatively,  if  i  prefer  the  appearance  of  the  switch()  statement  I  may  use  a  trick  like  the  one  nospam  at  please  dot  com  presents:

<?php
$mixed  =  0;
switch(TRUE){
      case  (NULL===$mixed):  //blah  break;
      case  (0    ===$mixed):  //etc.  break;  
}
?>

code  till  dawn!  mark  meves!  
ezekiel  at  superquenelles  dot  com
25-Mar-2004  10:40  
In  reply  to  Alex  Fung  :  
The  following  code  doesn't  work  :  

<?php  
$x  =  18;  
$y  =  6;  

switch  ($x)  {  
      case  (($y  *  4)  ||  (9  *  3)):  
              echo  "Member";  
              break;  
      default:  
              echo  "Not  a  member";  
}  
?>  

Why  :  
<design  at  hyperoptix  dot  com>  want  to  test  if  $x  ==  $y*4  or  $x  ==  9*3  ($x  ==  (($y*4)||(9*3))  
However  the  case  statement  evaluate  the  value  of  (($y*4)||(9*3))  that  is  always  true  because  9*3=27  (!=0)  
That's  why  this  code  always  return  true  when  $x  !=  0.  
The  correct  code  would  be  :  

<?php  
$x  =  18;  
$y  =  6;  

switch  ($x)  {  
      case  (($y  *  4)):  
      case  ((9*3)):  
              echo  "Member";  
              break;  
      default:  
              echo  "Not  a  member";  
}  
?>  

Boolean  logic  work  inside  case  statement,  you  just  need  to  know  that  the  expression  in  the  case  statement  is  first  evaluated  then  compared  with  the  evaluated  value  in  the  switch  statement.  
Alex  Fung
18-Mar-2004  07:06  
I  refer  to  the  "Boolean  logic  does  not  work  inside  case  statements"  example  by  "design  at  hyperoptix  dot  com"  at  "19-Feb-2004  12:46"  

I  found  that  his  code  fragment  is  working  perfectly  correct.  

<?php  
$x  =  18;  
$y  =  6;  

switch  ($x)  {  
      case  (($y  *  4)  ||  (9  *  3)):  
              echo  "Member";  
              break;  
      default:  
              echo  "Not  a  member";  
}  
?>  

I  don't  know  what  he  expects,  but  the  ||  evaluates  to  true.  Since  $8  ==  true,  it  echoes  "Member".  If  we  set  $x=0,  then  it  echoes  "Not  a  member".  
design  at  hyperoptix  dot  com
19-Feb-2004  04:46  
Boolean  logic  does  not  work  inside  case  statements:  

<?php  
$x  =  18;  
$y  =  6;  

switch  ($x)  {  
      case  (($y  *  4)  ||  (9  *  3)):  
              echo  "Member";  
              break;  
      default:  
              echo  "Not  a  member";  
}  
?>  

echoes  "Member".  
php  dot  net  dot  1  at  yogelements  dot  com
20-Jan-2004  03:39  
Declaring  a  variable  (actually  an  array)  as  static  w/in  a  switch{}  spun  my  wool  for  a  while:
don't:
<?
function  ss()  {
      switch  ("bug")  {
              case  "bug"  :
                      static  $test  =  "xyz";
                      break;
              default  :
                      static  $test  =  "abc";
      }
  echo  $test;
}
ss();  //abc
?>
do:
<?
function  tt()  {
      static  $test;
      switch  ("fix")  {
              case  "fix"  :
                      $test  =  "xyz";
                      break;
              default  :
                      $test  =  "abc";
      }
  echo  $test;
}
tt();  //  xyz
?>  
gmgiles  at  pacbell  dot  net
19-Jan-2004  06:07  
Did  you  know  that  switch()  and  case()  can  also  accomodate  things  like  basic  math  calculations  and  counter  incrementing?  They  do.  In  this  example,  I  use  a  switch  statement  (which  is  inside  of  a  while  loop)  to  alternate  the  background  color  of  a  table  row.  It  gives  me  a  cool  spool-printer-paper  effect.  

<?php  
$rows_per_color  =  5;    //  change  bgcolor  every  5  rows  
switch($ctr++)  {  
      case  0:  
              $bgcolor  =  "#ffffff";  
              break;  
      case  ($rows_per_color):  
              $bgcolor  =  "#ff0000";  
              break;                                
      case  ($rows_per_color  *  2):  
              $bgcolor  =  "#ffffff";  
              $ctr  =  1;  
              break;                
}  
?>  

As  you  can  see,  I  increment  $ctr  by  1  in  the  switch()  itself,  and  the  final  case()  does  a  simple  calculation.  Simple,  but  powerful.  [Remember,  the  above  example  is  inside  of  a  while()  loop...  each  time  it  iterates,  switch  increments  $ctr.]  
phpmanual  at  nos-pam  dot  sadlittleboy  dot  com
10-Jan-2004  10:32  
Regarding  bishop's  comment  below,  although  using:  
      switch($bug  ===  0  ?  ''  :  $bug)  {
may  work,  (  and  although  I  do  like  the  ternary  operator,  :)  it  might  be  more  intuitive/readable  to  use  this  instead:
      switch(  (string)$bug  )  {  
which  typecasts  the  variable  to  a  string  to  ensure  that  "0"  will  be  handled  correctly.  
jon
09-Dec-2003  05:48  
In  response  to  the  entry  by  "kriek  at  jonkriek  dot  com",  I  think  you  would  probably  be  better  of  doing  this:
<?php
      //  ensure  $_GET['go']  is  set,  an  integer,  and  not  0
      //  then,  set  nav  number;  default  to  1
      $nav  =  (  isset($_GET['go'])  &&  (intval($_GET['go'])  ==  $_GET['go'])  &&  $_GET['go']  )  ?
              intval($_GET['go'])  :  1;

      //  format  navigation  string  and  include
      include(sprintf("Page%02d.php",$nav));        
?>

...  as  oppposed  to  the  switch  setup  you  recommended,  which  is  limited  to  the  number  of  cases  you  specify...  
havar  at  henriksen  dot  nu
15-Sep-2003  05:54  
Remember,  that  you  also  could  use  functions  in  a  switch.  
For  example,  if  you  need  to  use  regular  expressions  in  a  switch:  

<?php  
$browserName  =  'mozilla';  
switch  ($browserName)  {  
    case  'opera':  
      echo  'opera';  
    break;  
    case  (preg_match("/Mozilla(  Firebird)?|phoenix/i",  $browserName)?$browserName:!$browserName):  
      echo  "Mozilla  or  Mozilla  Firebird";  
    break;  
    case  'konqueror':  
      echo  'Konqueror';  
    break;  
    default:  
      echo  'Default';  
    break;  
}  
?>  

or  you  could  just  use  a  regular  expression  for  everything:  

<?php  
$uri  =  'http://www.example.com';  
switch  (true)  {  
    case  preg_match("/$http(s)?/i",  $uri,  $matches):  
      echo  $uri  .  '  is  an  http/https  uri...';  
    break;  
    case  preg_match("/$ftp(s)?/i",  $uri,  $matches):  
      echo  $uri  .  '  is  an  ftp/ftps  uri...';  
    break;  
    default:  
      echo  'default';  
    break;  
}  
?>  
(cgibbard)  student  math  uwaterloo  ca
10-Aug-2003  06:30  
Just  in  reply  to  the  comment  about  2  digit  numbers:  something  octal  certainly  is  going  on.  Integer  literals  prefixed  with  a  "0",  like  in  C  and  several  other  languages,  are  treated  as  octal.  Similarly,  integer  literals  prefixed  with  "0x"  are  treated  as  hexadecimal.  Seeing  as  this  is  the  case,  08  and  09  are  not  valid  integer  literals.  It  turns  out  that  php  treats  them  as  0  (it  would  probably  be  better  to  fail  with  an  error  message,  but  it  doesn't).  Bottom  line?  Don't  prefix  numbers  with  0  in  code  unless  you  mean  octal.  Format  them  as  you  print  them  with  printf,  like  so:  printf("%02u",  $my_unsigned_int);  or  if  you  will,  use  sprintf  to  get  a  string  representation  rather  than  printing  on  stdout.  
bishop
14-Jul-2003  04:26  
As  jason  at  devnetwork  dot  net  and  others  have  pointed  out,  using  switch()  when  you  wish  to  compare  against  strings  can  be  dangerous:  

<?php  
$bug  =  0;  
switch  ($bug)  {  
      case  'fly':  
              echo  'flies  buzz';  
              break;  

      case  'mantis':  
              echo  'mantes  pray';  
              break;  

      default:  
              echo  'swat,  splat,  you  are  dead';  
              break;  
}  
?>  

Will  print  "flies  buzz",  NOT  "swat,  splat,  you  are  dead".  
Remember  PHP  says  that  'fly'  ==  0,  or  in  general  string  ==  0  is  true.  

Anyway,  avoid  that  with:  

<?php  
$bug  =  0;  
switch  ($bug  ===  0  ?  ''  :  $bug)  {  
      case  'fly':  
              echo  'flies  buzz';  
              break;  

      case  'mantis':  
              echo  'mantes  pray';  
              break;  

      default:  
              echo  'swat,  splat,  you  are  dead';  
              break;  
}  
?>  

Prints  out  what  you  expect:  

Swat  
Splat  
You  are  dead  

P.S.:  that's  an  empty  string  (single  quote  single  quote),  not  a  spurious  double  quote.  
shawn  at  evilest  dot  net
04-May-2003  06:50  
You  can  also  nest  switch  statements  inside  case  statements:  

<?php  
      //  Set  argument  handlers  
      $argv  =  explode(",",  urldecode(getenv('QUERY_STRING')));  
      $argc  =  array_shift($argv);  
      $argd  =  array_shift($argv);  
      $arge  =  array_shift($argv);  
?>  

      //  Begin  switching  

<?php  
      switch  ($argc)  {  
              case  'home':  {  
                          print('This  is  $argc,  home  case.');  
                      break;  
              }  
              case  'subsection':  {  
                              switch  ($argd)  {  
                                          case  'links':  {  
                                                      switch($arge)  {  
                                                              case  'display':  {  
                                                              print('This  is  $arge,  subsection,links,display  case.');  
                                                              break;  
                                                              }  
                                                      }  
                                      }  
                              }  
              }  
      }  
?>  
i  luv  spam
26-Apr-2003  03:46  
Noticed  some  odd  switch  behavior  worth  mentioning:

Switching  on  a  variable  set  as  $var="08"  and  forgetting  the  quotes  within  the  case  results  in  different  behavior  depending  on  the  two  digit  number  the  variable  is  set  to.

For  "01"  to  "07",  using  a  case  like
    case  01:
the  case  is  triggered.

For  "08"  or  "09"  the  case  is  skipped.

For  "10"  to  "12"  the  case  is  triggered.

Looks  like  something  octal  may  be  going  on.

Anyway,  not  a  problem  once  the  case  is  changed  to:
    case  "08":
as  it  should  have  been  from  the  start.    Just  odd.  
jason  at  devnetwork  dot  net
24-Mar-2003  07:51  
It  should  be  pointed  out  that  this:

<?php

$var  =  0;

switch  (  $var  )
{
      case  "something":
              $foo  =  "Broken";
              break;
      default:
              $foo  =  "Okay";
              break;
}

echo  $foo;

?>

Will  print  out  "Broken".    It's  not  broken,  because  in  PHP,  when  an  Integer  and  a  String  are  compared,  the  string  is  ==  0.    So  0  ==  "something".    However,  this  is  not  apparent.    switch()  does  not  do  type  checking.  
kriek  at  jonkriek  dot  com
05-Mar-2003  11:13  
Nice,  clean,  template  style  navigation.  In  most  cases  it  is  fifteen  percent  faster  to  use  switch/case/break  instead  of  if/elseif/else.  Of  course  this  depends  on  your  application  and  individual  code  results  do  very.  

<?php
      switch  ($_GET['go'])  {
              case  "1":  $inc  =  'Page01.php';
              break;
              case  "2":  $inc  =  'Page02.php';
              break;
              case  "3":  $inc  =  'Page03.php';
              break;
              case  "4":  $inc  =  'Page04.php';
              break;
              default:  $inc  =  'Page01.php';
              break;
      }
      include  ($inc);
?>  
jemore  at  m6net  dotdot  fr
14-Feb-2003  09:26  
siwtch()  made  always  a  type  conversion  before  comparing  all  the  case  value  (PHP4.3.0),  so  the  following  statement  
<?php
          //  $a  =  'abc0'  or  'abc1'  or  'abc2',  so  this  is  a  string
          switch  ($a)
          {
              case  'abc0'  :  $nb  +=  1;  break;
              case  'abc1'  :  $nb  +=  2;  break;
              case  'abc2'  :  $nb  +=  3;  break;
          }
?>
is  slower  than  the  following  statement
<?
          if  ($a  ===  'abc0')  $nb  +=  1;
          elseif  ($a  ===  'abc1')  $nb  +=  2;
          elseif  ($a  ===  'abc2')  $nb  +=  3;
?>
because  the  '==='  (3  equals  signs)  compare  value  without  type  conversion.  Using  a  if/elseif/elseif  structure  instead  of  switch/case/case  can  be  2  times  faster  (I  have  made  a  test)  
rmunn  at  pobox  dot  com
24-Jan-2003  04:21  
In  answer  to  njones  at  fredesign  dot  com,  what  you're  seeing  is  the  way  the  switch  statement  is  supposed  to  work.  The  switch  statement  evaluates  the  cases,  top  to  bottom,  until  it  finds  the  first  one  that  matches  the  value  being  switch()ed  on.  So,  for  example,  if  you  had:  

<?php  
switch(2)  {  
case  1:  echo  "One\n";  break;  
case  2:  echo  "Two\n";  break;  
case  3:  echo  "Three\n";  break;  
case  2:  echo  "Two  again\n";  break;  
}  
?>  

Only  "Two"  would  get  echoed.  "Two  again"  would  NOT  get  echoed,  because  once  the  first  case  matches,  the  rest  of  them  do  NOT  get  evaluated.  As  soon  as  a  matching  case  is  found,  the  statements  starting  at  that  case  get  executed  until  the  first  break,  then  control  flows  out  the  bottom  of  the  switch  block.  
theonly  dot  mcseven  at  gmx  dot  net
19-Jan-2003  01:44  
working  a  bit  around  with  it  I  found  out  that  it  is  not  possible  to  
compare  the  variable  with  two  different  values  in  one  step  like  this  
(system  running  a  w2k  server,  apache2.0.43  &  php430):  

<?php  
switch  ($myvar)  {  
  case  ("foo"  ||  "bar"):  //do  something  
  break;  
  case  ("other"):  //do  another  thing  
  break;  
  default:  
}  
?>  

rather  use:  

<?php  
switch  ($myvar)  {  
  case  ("foo"):  
  case  ("bar"):  //do  something  
  break;  
  case  ("other"):  //do  another  thing  
  break;  
  default:  
}  
?>  
turk162  at  ALLSPAM_hotmail  dot  com
03-Dec-2002  09:55  
On  PHP  V4.2.1,  running  on  IIS5  as  a  CGI,  I  found  an  anomaly  with  how  SWITCH  handled  strings.    I've  heard  that  this  problem  doesn't  exist  on  V4.2.3  on  Apache.

This  snippet  took  the  wrong  branch:

<?PHP
$wonum  =  '20010E0';
SWITCH  ($wonum):
      CASE  '20010D0';
          ECHO  "<BR>Branching  at  D  with  wonum:  "  .  $wonum;
          BREAK;
      CASE  '20010E0';
          ECHO  "<BR>Branching  at  E  with  wonum:  "  .  $wonum;
          BREAK;
ENDSWITCH;
?>

Type  casting  with  $wonum  =  (STRING)  '20010E0';  didn't  help.
Changing  the  order  of  the  CASEs  made  no  difference  (it  shouldn't,  but...)

What  did  work  was  using  MD5  to  force  a  string  comparison:

<?PHP
$wonum  =  MD5('20010E0');
SWITCH  ($wonum):
      CASE  MD5('20010D0');
          ECHO  "<BR>Branching  at  D  with  wonum:  "  .  $wonum;
          BREAK;
      CASE  MD5('20010E0');
          ECHO  "<BR>Branching  at  E  with  wonum:  "  .  $wonum;
          BREAK;
ENDSWITCH;
?>

Moral:  test  test  test  
hexa  at  h3xa  dot  com
14-Nov-2002  12:55  
this  is  a  simple  function  that  returns  a  random  string  and  uses  
switch  to  determine  what  kind  of  string  you  want.  
function  r(  [string  prefix][,int  type,][,int  chars]  );  

type  =  1  ->  only  numbers  
type  =  2  ->  only  letters  
type  =  3  ->  both  

<?php  
function  r($prefixo  =  "",$tipo  =  3,$numcaracteres  =  10)  {  
      switch  ($tipo)  {  
              case  1:  
                      for  ($x  =  1;  $x  <=  $numcaracteres;  $x++)  {  
                              $rnum  .=  chr(rand(48,57));  
                      }  
                      return  $prefixo  .  $rnum;  
                      break;  
              case  2:  
                      for  ($x  =  1;  $x  <=  $numcaracteres;  $x++)  {  
                              if  (rand(1,2)  ==  1)  {  $rletras  .=  chr(rand(65,90));  }  
                              else  {  $rletras  .=  chr(rand(97,122));  }  
                      }  
                      return  $prefixo  .  $rletras;  
                      break;  
              case  3:  
                      for  ($x  =  1;  $x  <=  $numcaracteres;  $x++)  {  
                              $r  =  rand(1,3);  
                              if  ($r  ==  1)  {  $rstring  .=  chr(rand(65,90));  }  
                              elseif  ($r  ==  2)  {  $rstring  .=  chr(rand(97,122));  }  
                              else  {  $rstring  .=  chr(rand(48,57));  }  
                      }  
                      return  $prefixo  .  $rstring;  
                      break;  
      }  
}  
?>  
chernyshevsky  at  hotmail  dot  com
28-May-2002  07:45  
Be  very  careful  when  you're  using  text  strings  as  cases.  If  the  variable  supplied  to  switch()  is  an  integer,  the  cases  would  be  converted  to  integer  before  the  comparison  is  made  (usually  to  zero).  The  following  snippet  prints  "hello".  

<?php  
$a  =  0;  
switch($a)  {  
  case  'Hello':  echo  "Hello";  
  break;  
  }  
?>  
paz  at  spiralon  dot  com
16-May-2002  11:44  
In  case  :  )  it  helps  someone,  I  was  able  to  clean  up  some  hairball  code  by  using  nested  switches  (didn't  see  it  mentioned  here).    Thanks  to  all  those  who  are  writing  examples  -  I  love  this  site!  

<?php  
$string_match="second";  
switch  ($string_match)  {  
case  "first":  
case  "second":  
case  "third":  
      print  "<H3>Something  for  all  three</H3><br>";  
      switch  ($string_match)  {  
          case  "first":  
          print  "something  for  first  only";  
          break;  
          case  "second":  
          case  "third":  
          print  "something  for  the  other  two";  
          break;  
      }  
break;  
default:  
print  "<H3>no  match</H3>";  
}  
?>  
miket  of  iopenmedia  dot  com
17-Apr-2002  04:05  
In  Response  To:  
----------------------  
joe@-SPAM-modjeski.net  
20-Jul-2000  08:39  

Just  my  2  bits.  Now  that  PHP4  supports  variable  function  arguments,  based  
on  example  2  you  should  be  able  to  assign  vars  like  this:  

<?php  
switch  (func_num_args()){  
    case  3:  
      $arg2  =  func_get_arg(2);  
    case  2:  
      $arg1  =  func_get_arg(1);  
    case  1:  
      $arg0  =  func_get_arg(0);  
break;  
}  
?>  

---------------------  

Why  not  just  do:  

<?php  
$num  =  func_num_args()  -  1;  
$arg{$num}  =  func_get_arg($num);  
?>  
gray  dot  quinn  at  catch-e  dot  com  dot  au
22-Mar-2002  03:00  
To  get  the  conditional  statement  to  work  for  the  above  example  use  this:  

<?php  
$chr  =  substr($a,$i,1);  
switch  (TRUE)  {  

case  $chr  ==  "&#6304;||  $chr  ==  "&#2208;||  $chr  ==  "&#14496;||  $chr  ==  "&#10428;/span>:  
$a  =  str_replace(substr($a,$i,1),"a",$a);  
break;  

case  $chr  ==  "&#39072;||  $chr  ==  "&#34976;||  $chr  ==  "&#43196;/span>:  
$a  =  str_replace(substr($a,$i,1),"e",$a);  
break;  
?>  

}  
PeterC  at  (spamme)rm-rfsplat  dot  com
07-Feb-2002  05:55  
Along  the  lines  of  using  expressions  in  switch  statements.    I  came  across  some  code  which  wrapped  switch  statements  in  'if'  blocks  like  so...
if  (isset($var)  {
      switch($var)  {
              ....
      

But  I  found  the  following  a  little  cleaner.

switch  (  isset($var)  ?  $var  :  defaultValue  )  {
...  
x@x
26-Jul-2001  06:29  
often  you  will  have  to  perform  multiple  actions  in  sequence,  but  this  sequence  must  be  broken  once  one  of  them  detects  a  stop  condition  (such  as  an  error,  when  validating  form  request  variables).  
One  way  is  to  use:  

if  (check1()  
&&  check2()  
&&  check3()  
)  valid();  
else  error();  

But  when  the  sequence  is  long  and  must  reordered,  this  can  be  errorprone  because  not  all  line  of  check  have  the  same  syntax  (imagine  that  you  want  to  comment  one  of  them).  

Another  way  is  to  rewrite  it  as:  

check1()  and  
check2()  and  
check3()  and  
...  
valid()  or  
error();  

The  above  syntax  does  not  fit  well  when  the  valid()  code  must  be  several  statements.  
An  alternative  syntax  can  be:  

switch  (false)  {  
case  check1():  
case  check2():  
case  check3():  
??error();  
??break;  
default:  
??valid();  
}  

This  last  equivalent  sample  show  you  that  each  case  expressions  is  evaluated,  until  one  of  them  evaluates  to  a  value  equal  (==)  to  the  switch  expression.  Above,  the  error()  code  will  only  be  called  if  one  of  the  check  evaluates  to  false.  And  the  valid()  code  will  only  be  evaluated  only  if  the  switch  reach  the  default,  which  means  that  none  of  the  above  check  returned  false...  
bensphpnetemail  at  supernaut  dot  org
30-Jun-2001  03:14  
It's  obvious,  but  might  still  bear  explicit  mention  that  you  can  conditionally  execute  the  BREAK  statement  in  order  to  allow  a  CASE  to  fall  through  to  the  next  CASE.    

e.g.:->  Here,  CASE  1  will  fall  through  and  the  DEFAULT  CASE  statements  will  also  be  executed  unless  $somevar  is  true.  

<?php  
switch  ($i)  {  
      case  0:  
              print  "i  equals  0";  
              break;  
      case  1:  
              print  "i  equals  1";  
              if  ($somevar)  {  
                          break;  
                          }  
      default;  
              echo  'Some  Default  Statements';  
              break;  
}  
?>  

Cheers,  
Ben  Nardone  
rtreat2  at  tampabay  dot  rr  dot  com
31-Mar-2001  08:34  
just  a  further  example  of  the  above  note,  you  can  do  the  following  type  of  searching:  

<?php  
switch  (true){  
      case  (  ereg  ("stats",$userfile_name)  ):  
              echo  "processing  stats";  
              process_stats();  
              break;    
      case  (  ereg("prices",$userfile_name)  ):  
              echo  "processing  prices";  
              process_prices();  
              break;    
      default:  
              echo  =  "File  not  recognized!!.";  
}  
?>  

this  script  could  be  used  to  determine  data  formats  for  uploaded  files  based  on  a  nameing  conve  
ntion.  just  one  example.  
nospam  at  please  dot  com
15-Nov-2000  10:18  
Just  a  trick  I  have  picked  up:  

If  you  need  to  evaluate  several  variables  to  find  the  first  one  with  an  actual  value,  TRUE  for  instance.  You  can  do  it  this  was.  

There  is  probably  a  better  way  but  it  has  worked  out  well  for  me.  

switch  (true)  {  

    case  (X  !=  1):  

    case  (Y  !=  1):  

    default:  
}  
joe  at  -SPAM-modjeski  dot  net
21-Jul-2000  12:39  
Just  my  2  bits.  Now  that  PHP4  supports  variable  function  arguments,  based  on  example  2  you  should  be  able  to  assign  vars  like  this:  

<?php  
switch  (func_num_args()){  
    case  3:  
      $arg2  =  func_get_arg(2);  
    case  2:  
      $arg1  =  func_get_arg(1);  
    case  1:  
      $arg0  =  func_get_arg(0);  
break;  
}  
?>

1590 view

4.0 stars