PHP如果不等于(!=)和或(||)问题.为什么不起作用? [英] PHP if not equal(!=) and or (||) issue. Why doesnt this work?
问题描述
我知道这是简单的PHP逻辑,但这根本行不通...
I know this is simple PHP logic but it just won't work...
$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>";
}
我在做什么错了?
推荐答案
我不确定您想要什么,但是该逻辑将始终为true
.您可能要使用AND(&&),而不是OR(||)
I am not exactly sure what you want, but that logic will always evaluate to true
. You might want to use AND (&&), instead of OR (||)
曾经测试过的最远的语句是($str != "danielle"
),并且当一条语句产生真值时,PHP进入该块只会有两种可能的结果.
The furthest statement that is ever tested is ($str != "danielle"
) and there are only two possible outcomes as PHP enters the block as soon as a statement yields true.
这是第一个:
$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:
If the OR was changed to AND then it keeps evaluating until a false is returned:
$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
尽管该解决方案无法很好地扩展,但您应保留一个排除列表数组,并对照该列表进行检查:
The solution doesn't scale well though, you should keep an array of the exclude list and check against that do:
$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>";
}
这篇关于PHP如果不等于(!=)和或(||)问题.为什么不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!