Page 1 of 1

[SOLVED] Switch Statement Evaluation

Posted: Thu Mar 03, 2005 3:30 pm
by Crashin
Do switch statements evaluate a variable and compare it's value regardless of whether or not it's set? And, if so, do you need to wrap the switch statement with an if statement to avoid this?

For example:

Code: Select all

<?php
//switch.php

switch ($_POST&#1111;'a']) &#123;
  case '1':
    echo "ONE!<br>";
    break;
  default:
    echo "DEFAULT!<br>";
    break;
&#125;

if (isset($_GET&#1111;'b'])) &#123;
  echo "BEE!<br>";
&#125;

echo "<a href="switch.php?b=go">GO!</a>";
?>
If the GO! link is clicked (or, upon initial loading, for that matter):

Code: Select all

DEFAULT!
So, do you have to wrap the switch statement to get it to work the way you expect, or am I missing something?

Eg:

Code: Select all

<?php
//switch.php

if (isset($_POST&#1111;'a'])) &#123;
  switch ($_POST&#1111;'a']) &#123;
    case '1':
      echo "ONE!<br>";
      break;
    default:
      echo "DEFAULT!<br>";
      break;
  &#125;
&#125;

if (isset($_GET&#1111;'b'])) &#123;
  echo "BEE!<br>";
&#125;

echo "<a href="switch.php?b=go">GO!</a>";
?>

Posted: Thu Mar 03, 2005 3:35 pm
by John Cartwright
your switch statement generally should be done in a way that the default or invalid value is the one you would expect when there is no value set for the variable. Either way is valid though.

Posted: Thu Mar 03, 2005 3:53 pm
by Crashin
Thanks, Phenom. I guess I always thought that if the variable the switch statement is evaluating isn't set, the switch statement doesn't execute. I've used them for a long time, but never in a way that caused this issue to pop up.

You see! You learn something new everyday. :D