开发者

if / else simplification to ternary operator

Can this be done for the code below. Problem I see is that there are two statements in the else clause and I couldn't figure out a way to fit in the echo...I need to 开发者_运维知识库return a 1 or a 0. Perhaps someone knows a trick?

  function empty_user($c)    
    {
    if((int)!in_array('',$this->a,TRUE)) 
      {
      return 1;
      }
     else
      {
      echo $c;
      return 0;
      } 
    }


No ternary =/. Although you can simplify this a lot because once the function returns, it stops interpreting the function anyway, so you can eliminate the else.

function empty_user($c) {
    if ((int)!in_array('',$this->a,TRUE)) return 1;
    echo $c;
    return 0;
}


you generally shouldn't use ternary operators to determine execution order, but also, no, you won't be able to convert the if/else you've got there.


You can't use a ternary operator if you want more than one operation in either block, but the question is why would you want to? It is much clearer and easier to update if you have full blocks that you can continue to add code to.


in_array returns a bool which is perfect for an if statement - there is no need to cast it to an int.

    function empty_user($c)    
    {
       if (in_array('',$this->a,TRUE))
       {
          echo $c;
          return 0;
       }

       return 1;
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜