[SOLVED] Switch Statement Evaluation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Crashin
Forum Contributor
Posts: 223
Joined: Mon May 06, 2002 3:42 pm
Location: Colorado

[SOLVED] Switch Statement Evaluation

Post 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>";
?>
Last edited by Crashin on Thu Mar 03, 2005 3:50 pm, edited 2 times in total.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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.
User avatar
Crashin
Forum Contributor
Posts: 223
Joined: Mon May 06, 2002 3:42 pm
Location: Colorado

Post 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
Post Reply