dsfds2343
2017-02-02 08:53
浏览 26
已采纳

在php中使用逆条件顺序在if else条件下使用OR

I am trying to get "OK" if my condition False, i want to keep same if else order as given example, don't advice to move "else" content in "if" and "if" content in "else",

 <?php

    //Case 1 Both False
    //$point = 1001; //more than 100
    //$flag  = 1;   //flag is = 0 

    //Case 2 First False Second True
    //$point = 1000; //less than 1000
    //$flag  = 0;   //flag is = 0 

    //Case 3 First TRUE Second FALSE
    //$point = 100; //less than 100
    //$flag  = 1;   //flag is = 1 

    $point = 1001;
    $flag  = 1;   
    ?>

    <div class="box border">
    <div class="box-title">
    <?php if($flag == 0 || $point < 1000) { ?>
    <h4>Not OK</h4>
    <?php } else { ?>
    <h4>OK</h4>
    <?php }?>
    </div>

in above script //Case 1 is working but Case 2 and Case 3 both not working with OR operator

I want all 3 cases work in same pattern

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douqiao1413 2017-02-02 10:33
    已采纳

    After reading your comments:

    It seems you want to show some score (in the else-branch of an if-then-else) if the user has equal/more than 1000 points or you toggle a flag (which basically means "always show points").

    Normally you'd be doing that in the if-branch:

    if ($flag || $point >= 1000)
    {
        echo "OK";
    } else {
        echo "Not OK";
    }
    

    Since you want the Not OK to be in the if-Branch you need to inverse the condition, doing so means inverting every part of the condition and the operators aswell:

    • $flag becomes !$flag
    • $point >= 1000 becomes $point < 1000
    • || becomes &&

    Result:

    if (!$flag && $point < 1000)
    {
        echo "Not OK";
    } else {
        echo "OK";
    }
    

    Writing this into a truth-table:

    flag        point       result
    0           < 1000      Not OK
    1           < 1000      OK
    0           >=1000      OK
    1           >=1000      OK
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douyo770657 2017-02-02 09:07

    I tested this code and it works.

    if(!($flag != 0 || $point >= 1000)){
        echo "Not OK";
    }else{
        echo "OK";
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题