user656925
user656925

Reputation:

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;
      } 
    }

Upvotes: 0

Views: 146

Answers (4)

Korvin Szanto
Korvin Szanto

Reputation: 4501

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;
}

Upvotes: 3

Paul
Paul

Reputation: 6871

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;
    }

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191729

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.

Upvotes: 3

nathan gonzalez
nathan gonzalez

Reputation: 11987

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.

Upvotes: 3

Related Questions