【问题标题】:PHP "or" not working in multi-part conditionalPHP“或”不能在多部分条件下工作
【发布时间】:2014-04-21 10:29:41
【问题描述】:

我正在尝试做一个工作周检测器,即周一至周五:

if (($nowday == "thu"||"thu")) 

当 $nowday 为 TRUE 时给出 TRUE

if (($nowday == "thu")) 

给出错误! $nowday 仍然坐着。显然这是对的。为什么我得到的是假的?

我疯了还是不是 PHP 中的 OR 运算符 || ?

【问题讨论】:

  • 您的第一个 if 条件不正确。如果您执行if(1){echo 'true';} 也是同样的情况,这将是true,因为它没有与任何东西进行比较。
  • 好的,伙计们(还有女孩?)我很抱歉没有早点说谢谢。我也一直在思考很长时间,但是,你知道事情一直在妨碍你,然后你就忘记了等等。没有任何借口,非常抱歉,但非常感谢。
  • 这个帖子过早地发布了,我在研究一些相当不错的 CSS 时编辑超时,所以......但非常感谢你。我带着阵列去了,它就像一个魅力。

    我仍然对 PHP OR 运算符的操作完全感到困惑,但很快就会在某个阶段开始一个新的学术讨论线程。当我把它贴在这里(可能是今天晚些时候)时,我会在这里贴一张便条。我也应该承认我的原始帖子非常模糊 - 但你让我明白了。来自毛伊岛的 Mahalo nui loa 和 Aloha :-)
  • @user3424997:如果其中一个答案帮助您解决了问题,请将其标记为accepted

标签: php boolean


【解决方案1】:

为什么它不起作用?

无论变量值如何,您的条件表达式将始终计算为TRUE

if (($nowday == "thu"||"thu")) 

案例1:当$nowdaythu时:

1. (($nowday == "thu") || "thu") // precedence grouping
2. (TRUE || "thu")               // ("thu" == "thu") is TRUE
3. (TRUE || TRUE)                // because non-empty string evaluates to TRUE
4. (TRUE)  

案例2:当$nowdaysat时:

1. (($nowday == "sat") || "thu") // precedence grouping
2. (FALSE || "thu")              // ("thu" == "sat") is FALSE
3. (FALSE || TRUE)               // non-empty string evaluates to TRUE
4. (TRUE)  

如何解决这个问题?

如果您只是想检查$nowday 是否为thu,那么为什么需要将条件写两次?只需使用以下内容:

if ($nowday == "thu")

如果您需要检查$nowday任一 thu 还是sat,您可以这样写:

if ($nowday == "thu" || $nowday == "sat") 

或者,您可以用括号分隔表达式。这样,您可以确定评估条件的顺序。如果它们没有括在括号中,则根据 precedence 评估它们:

if ( ($nowday == "thu") || ($nowday == "sat") ) 

如果要查看多天,可以使用in_array()

$days = array('thu', 'fri', 'sat', /* ... */);

if (in_array($nowday, $days)) {
    // day is one of the days defined in the array
}

【讨论】:

    【解决方案2】:
    if (($nowday == "thu"||"thu"))
    

    是说如果$nowday == "thu" OR 如果"thu"if("thu") 始终为 TRUE,因为字符串“thu”不为空。这就是为什么您的条件语句会返回 TRUE 并将始终返回 TRUE

    你应该这样写你的条件语句:

    if (($nowday == "thu"|| $nowday == "thu"))
    

    但这可以简化为:

    if ($nowday == "thu")
    

    【讨论】:

    • 但是==的运算符优先级高于||
    • "thu"||"thu" 当然是TRUE,但我认为这从未被评估过。它评估($nowday == "thu") || "thu"
    猜你喜欢
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多