dqkx69935 2012-06-26 00:38 采纳率: 100%
浏览 44
已采纳

嵌套if语句好还是坏?

I have a vote system that allows users to vote for items. Right now I am doing it by checking first if the user is logged in and then checking to see if they have already voted. I am wondering if there is a better way of doing this as I have been told that nested if statements are something to avoid.

My code:

if ($loggedIn) {
    if($row['voted']){
        You Already voted
    }else{
        <a href="#">Agree</a>
    }
}else{
    Please Register
}
  • 写回答

4条回答 默认 最新

  • dongyi1524 2012-06-26 02:42
    关注

    Nested if( ... ){ ... }else{ ... } statements are fine, so long as they are logical and easy to read/maintain. Another option is to review the logic of your arguments and see if they can be expressed in a simpler fashion.

    For example, your provided code could be expressed as:

    if( !$loggedIn ){
      echo 'Please Register';
    }elseif( $row['voted'] ){
      echo 'You Already voted';
    }else{
      echo '<a href="#">Agree</a>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!