我似乎无法弄清楚为什么这不能正常工作。以下是设置的变量,但在“type”的最终结果中,它将其设置为m而不是fm
cpanel_notifications - 1
remote_server - 1
if ($_POST['cpanel_notifications'] == 1){
$type = "m";
}
elseif($_POST['cpanel_notifications'] == 0){
$type = "nm";
}
elseif($_POST['cpanel_notifications'] == 1 && $_POST['remote_server'] == 1){
$type = "fm";
}
elseif($_POST['cpanel_notifications'] == 0 && $_POST['remote_server'] == 0){
$type = "fnm";
}
结果:m
答案 0 :(得分:7)
这是因为第一个if
语句为真。没有理由去任何elses
。
答案 1 :(得分:2)
您需要做的是重新排序if's
if($_POST['cpanel_notifications'] == 1 && $_POST['remote_server'] == 1){
$type = "fm";
}
elseif($_POST['cpanel_notifications'] == 0 && $_POST['remote_server'] == 0){
$type = "fnm";
}
elseif ($_POST['cpanel_notifications'] == 1){
$type = "m";
}
elseif($_POST['cpanel_notifications'] == 0){
$type = "nm";
}
答案 2 :(得分:1)
只需更改条件顺序
if ($_POST['cpanel_notifications'] == 1){
if ($_POST['remote_server'] == 1) {
$type = "fm";
} else {
$type = "m";
}
}
elseif($_POST['cpanel_notifications'] == 0){
if ($_POST['remote_server'] == 0) {
$type = "fnm";
} else {
$type = "nm";
}
}
甚至
if ($_POST['cpanel_notifications'] == 1){
$type = ($_POST['remote_server'] == 1?"fm":"m");
}
elseif($_POST['cpanel_notifications'] == 0){
$type = ($_POST['remote_server'] == 0?"fnm":"nm");
}
答案 3 :(得分:1)
我同意这些意见,指明将您的陈述更多地移动到多个条件。作为一般经验法则,您希望将最具体的语句放在最上面,并在条件列表中更加通用。
答案 4 :(得分:-1)
添加更多=
if ($_POST['cpanel_notifications'] === 1){
$type = "m";
}
elseif($_POST['cpanel_notifications'] === 0){
$type = "nm";
}
elseif($_POST['cpanel_notifications'] === 1 && $_POST['remote_server'] === 1){
$type = "fm";
}
elseif($_POST['cpanel_notifications'] === 0 && $_POST['remote_server'] === 0){
$type = "fnm";
}
http://php.net/manual/en/language.operators.comparison.php
以上链接显示了添加额外=符号的原因。