我可以在 php 中的开关内使用 if 语句吗?
Can I use an if statement inside of a switch in php?
这是我想要做的:
我有一个名为 $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 />";
}
现在它会自动进入默认状态。它可以运行,但我想整合这两个限定符,我该怎么做?
您需要将 break
放在 switch 语句中每个案例的末尾,否则它会跳转到下一个案例。我还认为您可能对 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 />";
}
这是我想要做的:
我有一个名为 $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 />";
}
现在它会自动进入默认状态。它可以运行,但我想整合这两个限定符,我该怎么做?
您需要将 break
放在 switch 语句中每个案例的末尾,否则它会跳转到下一个案例。我还认为您可能对 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 />";
}