5

I'm using switch statement on $_POST method and my script runs correctly but I think my code is not in a right way.

Here's my code:

<?php

switch(isset($_POST))
{
    case isset($_POST['A']):
      //do something
    break;
    case isset($_POST['B']):
      //do something
    break;
    case isset($_POST['C']):
      //do something
    break;
}

?>

my script runs correctly but I think my switch statement is not GOOD enough. Is there more simplier way or BETTER way using switch statement and $_POST method?

4

4 回答 4

8

这太可怕了,但我比 if-else-evil-chain 更喜欢这个:

switch(true)
{
    case isset($_POST['A']):
      //do something
    break;
    case isset($_POST['B']):
      //do something
    break;
    case isset($_POST['C']):
      //do something
    break;
}
于 2013-10-28T14:46:43.350 回答
6

看一下这个 ;)


if (!empty($_POST)) {

         switch ($_POST) {
        case $_POST['A']:
            #do something;
            break;
        case $_POST['B']:
            #do something;
            break;
        case $_POST['C']:
            #do something;
            break;
    }
}
于 2016-05-02T07:55:44.280 回答
3

也许你的意思是类似的?

<?php

if(isset($_POST['A'])){
 // do something
}
if(isset($_POST['B'])){
 // do something
}
if(isset($_POST['C'])){
 // do something
}

?>

(这会执行所有不同的匹配分支,而不仅仅是第一个。如果您只想执行第一个匹配的分支,请将 non-first 更改为。ifelseif

于 2013-10-28T14:45:52.533 回答
2

放置方法的一个好switch (){ case: }方法是:

if (condition){
   // Do Something    
}elseif(condition){
   // Do Something
}elseif(condition){
   // Do Something    
}

这条链看起来很可怕,但我建议在你的独特情况下使用一些东西,alternativley 你可以使用@lame-up-ducks 答案,但这是我个人建议使用的

于 2013-10-28T14:51:06.240 回答