doulu4316 2011-10-20 09:19
浏览 34
已采纳

你看到这个破裂吗? 任何问题? 简单的php if elseif语句

I'm a total PHP newb, so there is probably a better way of outputting a row's class based on different variables.

Is this bad, and if it is why is it?

    if ($variable1 > 0 && $variable2 != 2)  {
        echo "<tr class='variable1'>";
        }
        elseif ($variable2==2)
        {
         echo "<tr class='variable2'>";
        }
        else {
              echo "<tr>";
                 }
  • 写回答

7条回答 默认 最新

  • dongqu2863 2011-10-20 09:33
    关注

    I would write it like this:

    $class_name = '';
    if (2 == $variable2)
    {
        $class_name = 'variable2';
    }
    elseif ($variable1 > 0)
    {
        $class_name = 'variable1';
    }
    echo '<tr class="' , $class_name , '">';
    

    notice that on the equality test I use the constant before the variable.. this is a habit so that if I miss one equal it would result in an error that I would be forced to correct it instead of a "strange" behavior

    another thing is that I give the initial value to $class_name and that will be the default one

    also I use apostrophes instead of quotation marks because it is faster (because the way you did it php will parse the string for variables)

    and the last thing is that I echo multiple string.. that's also faster than concatenating 3 strings (

    echo '<tr class="' , $class_name , '">'; 
    

    and not echo

    '<tr class="' . $class_name . '">';
    

    )

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题