我知道这是简单的PHP逻辑,但它不会起作用......
$str = "dan";
if(($str != "joe")
|| ($str != "danielle")
|| ($str != "heather")
|| ($str != "laurie")
|| ($str != "dan")){
echo "<a href='/about/".$str.".php'>Get to know ".get_the_author_meta('first_name')." →</a>";
}
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
Gaz*_*ler 40
我不完全确定你想要什么,但这种逻辑总会评估为true
.您可能想要使用AND(&&),而不是OR(||)
经过测试的最远的语句是($str != "danielle"
),只有两个可能的结果,因为一旦语句产生true,PHP就会进入块.
这是第一个:
$str = "dan";
$str != "joe" # true - enter block
$str != "danielle" #ignored
$str != "heather" #ignored
$str != "laurie" #ignored
$str != "dan" #ignored
Run Code Online (Sandbox Code Playgroud)
这是第二个:
$str = "joe";
$str != "joe" # false - continue evaluating
$str != "danielle" # true - enter block
$str != "heather" #ignored
$str != "laurie" #ignored
$str != "dan" #ignored
Run Code Online (Sandbox Code Playgroud)
如果OR被更改为AND,则它会一直进行评估,直到返回false:
$str = "dan";
$str != "joe" # true - keep evaluating
$str != "danielle" # true - keep evaluating
$str != "heather" # true - keep evaluating
$str != "laurie" # true - keep evaluating
$str != "dan" # false - do not enter block
Run Code Online (Sandbox Code Playgroud)
虽然解决方案不能很好地扩展,但是你应该保留一个排除列表的数组并检查它:
$str = "dan";
$exclude_list = array("joe","danielle","heather","laurie","dan")
if(!in_array($str, $exclude_list)){
echo " <a href='/about/".$str.".php'>Get to know ".get_the_author_meta('first_name')." →</a>";
}
Run Code Online (Sandbox Code Playgroud)
joa*_*rom 10
另一种方法是
$name = 'dan';
$names = array('joe', 'danielle', 'heather', 'laurie', 'dan');
if(in_array($name,$names)){
//the magic
}
Run Code Online (Sandbox Code Playgroud)
欢迎使用布尔逻辑:
$str = 'dan'
$str != "joe" -> TRUE, dan is not joe
$str != "danielle" -> TRUE, danielle is not dan
$str != "heather") -> TRUE, heather is not dan
$str != "laurie" -> TRUE, laurie is not dan
$str != "dan" -> FALSE, dan is dan
Run Code Online (Sandbox Code Playgroud)
布尔逻辑真值表如下所示:
和:
TRUE && TRUE -> TRUE
TRUE && FALSE -> FALSE
FALSE && FALSE -> FALSE
FALSE && TRUE -> FALSE
Run Code Online (Sandbox Code Playgroud)
要么:
TRUE || TRUE -> TRUE
TRUE || FALSE -> TRUE
FALSE || TRUE -> TRUE
FALSE || FALSE -> FALSE
Run Code Online (Sandbox Code Playgroud)
你的陈述归结为:
TRUE || TRUE || TRUE || TRUE || FALSE -> TRUE
Run Code Online (Sandbox Code Playgroud)
根据您在Glazer的答案中的评论,看起来您想要输入if块,$str
而不是列出的名称之一.
在这种情况下,如果你把它写成,它会更具可读性
if( !( ($str == "joe") || ($str == "danielle") || ($str == "heather") || ($str == "laurie") || ($str == "dan") ) )
Run Code Online (Sandbox Code Playgroud)
这实际上读为"如果不是这些人的一个......"的人在看你的代码.这相当于稍微不那么明显
if( ($str != "joe") && ($str != "danielle") && ($str != "heather") && ($str != "laurie") && ($str != "dan") )
Run Code Online (Sandbox Code Playgroud)
它们等价的事实在逻辑上被称为德摩根定律.