PHP,如果不是语句 [英] PHP if not statements
问题描述
这可能是设置服务器的方式,但是我把头撞在墙上.我想说的是,如果$action
没有值或具有非"add"或"delete"的值,则出现错误,否则继续运行脚本.但是,无论$action
是什么,我都会出错.
This may be the way my server is set up, but I'm banging my head against the wall. I'm trying to say that if $action
has no value or has a value that is not "add" or "delete" then have an error, else keep running the script. However, I get an error no matter what $action
is.
$action = $_GET['a'];
if((!isset($action)) || ($action != "add" || $action != "delete")){
//header("location:index.php");
echo "error <br>";
}
$action
的设置正确,如果运行类似if($action =="add")
的命令,它将起作用.这是在我的本地主机上,因此可能是设置问题.
$action
is being set properly and if run something like if($action =="add")
it works. This is on my local host, so it could be a settings issue.
推荐答案
您的逻辑略有偏离.第二个||
应该是&&
:
Your logic is slightly off. The second ||
should be &&
:
if ((!isset($action)) || ($action != "add" && $action != "delete"))
您可以通过尝试一个样本值来查看为什么原始行会失败.假设$action
是"delete"
.条件逐步降低的方法如下:
You can see why your original line fails by trying out a sample value. Let's say $action
is "delete"
. Here's how the condition reduces down step by step:
// $action == "delete"
if ((!isset($action)) || ($action != "add" || $action != "delete"))
if ((!true) || ($action != "add" || $action != "delete"))
if (false || ($action != "add" || $action != "delete"))
if ($action != "add" || $action != "delete")
if (true || $action != "delete")
if (true || false)
if (true)
糟糕!条件刚刚成功并显示错误",但是应该失败了.实际上,如果考虑一下,无论$action
的值是多少,两个!=
测试之一将返回true.将||
切换为&&
,然后倒数第二行变为if (true && false)
,该行会适当地减少为if (false)
.
Oops! The condition just succeeded and printed "error", but it was supposed to fail. In fact, if you think about it, no matter what the value of $action
is, one of the two !=
tests will return true. Switch the ||
to &&
and then the second to last line becomes if (true && false)
, which properly reduces to if (false)
.
顺便说一句,有一种方法可以使用||
并进行测试.您必须使用迪摩根定律(即:
There is a way to use ||
and have the test work, by the way. You have to negate everything else using De Morgan's law, i.e.:
if ((!isset($action)) || !($action == "add" || $action == "delete"))
您可以用英语将其读为如果没有行动(添加或移除),那么".
You can read that in English as "if action is not (either add or remove), then".
这篇关于PHP,如果不是语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!