Reputation: 602
I have a conflict regarding else condition. I can write a program in 2 ways.
Method 1
$msg = '';
if(cond)
{
$msg = 'success';
}
else
{
$msg = 'error';
}
Method 2
$msg = 'error';
if(cond)
{
$msg = 'success';
}
Can you please tell me which method is better and how? Thanks
Upvotes: 0
Views: 81
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/else
Also you should call this thing "Approach", not a "method", because a method is a function within a class.
Upvotes: 1
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
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
Reputation: 5213
Use the ternary operator:
$msg = (cond) ? 'success' : 'error';
Upvotes: 1