Jump to content

Switch Statement Bugger Me


President Obama

Recommended Posts

I couldn't understand switch statements in .net and I still don't get them with php. Can someone turn this into a switch statement, I just can't wrap my head around then.

if (isset($_POST['news'])){
add($_POST['text']);
header("location: admin.php");

} elseif (isset($_POST['rnews'])){
deletenews($_POST['number']);
header("location: admin.php");

} elseif (isset($_POST['taddm'])){
taddmember($_POST['website'], $_POST['name']);
header("location: admin.php");

} elseif (isset($_POST['tdelm'])){
tdeletemember($_POST['number']);
header("location: admin.php");

} elseif (isset($_POST['addm'])){
addmember($_POST['website'], $_POST['name']);
header("location: admin.php");

} elseif (isset($_POST['delm'])){
deletemember($_POST['number']);
header("location: admin.php");

} elseif (isset($_POST['tnews'])){
tadd($_POST['text']);
 header("location: admin.php");

} elseif (isset($_POST['trnews'])){
tdelete($_POST['number']);
header("location: admin.php");

} elseif (isset($_POST['video'])){
videoupdate($_POST['link']);
header("location: admin.php");

} else {
echo " Failed";
}

Link to comment
https://forums.phpfreaks.com/topic/224790-switch-statement-bugger-me/
Share on other sites

Switches are like a limited, inflexible version of if/then/else.  They only work with one variable, and you have to list the exact values that variable can take.

 

Let's say you use $_POST['mode'] to tell your script what mode to run in.  Then you can do like this:

 

switch($_POST['mode']) {
  case 'register':
    # Do register stuff
    break;
  case 'login':
    # Do login stuff
    break;
  default:
    # Handle unrecognized case
}

 

The advantage of a switch is that it enforces a good coding practice - it can reduce complexity of your code by forcing you to deal with a single variable with clearly defined values.  You can't cheat with a switch because php won't allow it.

Your code could also be put in a switch, you would just need to test for the bool true. (I wouldn't generally recommend this though).

 

switch (true) {
  case isset($_POST['news']):
    add($_POST['text']);
    header("location: admin.php");
    break;
  case isset($_POST['rnews']):
    deletenews($_POST['number']);
    header("location: admin.php");
    break;
  // etc etc
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.