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 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件