Iqbal Malik
Iqbal Malik

Reputation: 602

Else statement usage

I have a conflict regarding else condition. I can write a program in 2 ways.

  1. Method 1

    $msg = '';
    if(cond)
    {
        $msg = 'success';
    }
    else
    {
        $msg = 'error';
    }
    
  2. Method 2

    $msg = 'error';
    if(cond)
    {
        $msg = 'success';
    }
    

Can you please tell me which method is better and how? Thanks

Upvotes: 0

Views: 81

Answers (4)

Yang
Yang

Reputation: 8711

Code readability matters, so I'd use ternary operator when it really simplifies the look. Consider this,

function foo($stuff) {

  $var = null;

  if ($stuff === true) {
    $var = true;
  } else {
    $var = false;
  }

  return $var !== null ? true : false;
}

Since in this case, return $var !== null ? true : false is pretty short, it can be considered as "easy to read and understand".

Consider this,

function foo($stuff) {

  $var = null;

  if ($stuff === true) {
    $var = true;
  } else {
    $var = false;
  }

  if ($var !== null) {
     return true;
  } else {
     return false;
  }
}

The same thing, but a little bit longer

Conclusion

  • if a condition isn't that long, it's okay to stick with ternary operators (Because of readability). But if its not, then you'd better stick with if/else

Also you should call this thing "Approach", not a "method", because a method is a function within a class.

Upvotes: 1

Amal Murali
Amal Murali

Reputation: 76636

Between the two, I'd choose the first one.

$msg = '';
if(cond) { 
    $msg = 'success'; 
} else { 
    $msg = 'error'; 
}

This is readable and clearly conveys what it's trying to do. If the condition is true, the message will be success. If not, the message will be error.

But for something really simple as above, I'd use a ternary statement instead. It's very useful and can cut down code, but may make your code unreadable in some cases:

$msg = (cond) ? "success" : "error";

Pretty cool, right? Read more about ternary operators here.

Upvotes: 3

SuperTron
SuperTron

Reputation: 4243

I'd say the second one is better cause it's less lines and it has a default behavior. No matter what, you know that $msg will contain something, even if you add other checks down the road. However, I would use the Ternary operator in this case:

$msg = (cond) ? 'success' : 'error';

Upvotes: 1

theftprevention
theftprevention

Reputation: 5213

Use the ternary operator:

$msg = (cond) ? 'success' : 'error';

Upvotes: 1

Related Questions