我可以在php的开关中使用if语句吗?

时间:2015-02-26 04:58:35

标签: php forms if-statement switch-statement

继承人我想做的事情:

我有一个名为$ user的变量,其中的信息是从表单发布的。如果表单数据为空,我想做一件事,如果表单数据只是一个逗号或符号我想做另一件事,如果表单数据是正确的,我想做第三件事。这就是我设置的方式,这会有用吗?如果没有,我该怎么做才能使它发挥作用?

switch($user){
    case 1:
if(empty($user)){
echo "<h2>"."<strong>"."You entered NOTHING, PLEASE Re-Enter"."</strong>"."</h2>";
}
case 2:
if($user == ",") {
echo "<h2>"."<strong>"."You did not enter any valid names/abbreviations to search, PLEASE Re-Enter"."</strong>"."</h2>";
}
default:


    print "==========================================="."<br />";
    tester($company, $user);


print "==========================================="."<br />";
print "========The following were NOT found====="."<br />";
notFound($company, $user);

print "==========================================="."<br />";

}

现在它会自动进入默认状态。它运行,但我想整合两个限定符,我将如何去做呢?

1 个答案:

答案 0 :(得分:0)

您需要在switch语句中将break放在每个案例的末尾,否则它会落到下一个案例中。我也认为你可能对switch的工作方式感到困惑。如果你打开$ user,case会匹配$ user的值 - 所以你甚至不需要if语句。

switch($user){
    case "":
        echo "<h2>"."<strong>"."You entered NOTHING, PLEASE Re-Enter"."</strong>"."</h2>";
        break;
    case ",":
        echo "<h2>"."<strong>"."You did not enter any valid names/abbreviations to search, PLEASE Re-Enter"."</strong>"."</h2>";
        break;
    default:
        print "==========================================="."<br />";
        tester($company, $user);


        print "==========================================="."<br />";
        print "========The following were NOT found====="."<br />";
        notFound($company, $user);

        print "==========================================="."<br />";
}