我知道这是简单的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>";
}
我做错了什么?
答案 0 :(得分:39)
我不确定你想要什么,但该逻辑将始终评估为true
。您可能希望使用AND(&amp;&amp;)而不是OR(||)
经过测试的最远的语句是($str != "danielle"
)并且只有两个可能的结果,因为一旦语句产生true,PHP就会进入块。
这是第一个:
$str = "dan";
$str != "joe" # true - enter block
$str != "danielle" #ignored
$str != "heather" #ignored
$str != "laurie" #ignored
$str != "dan" #ignored
这是第二个:
$str = "joe";
$str != "joe" # false - continue evaluating
$str != "danielle" # true - enter block
$str != "heather" #ignored
$str != "laurie" #ignored
$str != "dan" #ignored
如果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
虽然解决方案不能很好地扩展,但是你应该保留一个排除列表的数组并检查它:
$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>";
}
答案 1 :(得分:10)
另一种方法是
$name = 'dan';
$names = array('joe', 'danielle', 'heather', 'laurie', 'dan');
if(in_array($name,$names)){
//the magic
}
答案 2 :(得分:7)
欢迎使用布尔逻辑:
$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
布尔逻辑真值表如下所示:
和
TRUE && TRUE -> TRUE
TRUE && FALSE -> FALSE
FALSE && FALSE -> FALSE
FALSE && TRUE -> FALSE
或:
TRUE || TRUE -> TRUE
TRUE || FALSE -> TRUE
FALSE || TRUE -> TRUE
FALSE || FALSE -> FALSE
你的陈述归结为:
TRUE || TRUE || TRUE || TRUE || FALSE -> TRUE
答案 3 :(得分:6)
根据您在Glazer答案中的评论,当$str
不是列出的名称之一时,您似乎想要输入if块。
在这种情况下,如果将其写为
,它将更具可读性if( !( ($str == "joe") || ($str == "danielle") || ($str == "heather") || ($str == "laurie") || ($str == "dan") ) )
这实际上读取为“如果它不是这些人中的一个......”给看着你代码的人。
相当于稍微不那么明显if( ($str != "joe") && ($str != "danielle") && ($str != "heather") && ($str != "laurie") && ($str != "dan") )
它们相同的事实在逻辑上被称为德摩根定律。
答案 4 :(得分:2)
试试这个
$str = "dan";
if($str == "joe" || $str == "daniella" || $str == "heather" || $str == "laurine" || $str == "dan"){ ... }
答案 5 :(得分:0)
比较两个字符串时,必须使用strcmp()。