4

This code works for what I want, but I'm wondering if it's ok to do nothing inside the curly brackets of an if statement. Is there a better way to write this?

if(empty($data) || $data == "unanswered")) {
//do nothing
} else {
    //display data
    echo $data;
}
2
  • 2
    Why wouldn't you use the inverted test? i.e. if(!empty($data) && $data != "unanswered"))
    – tdk001
    Aug 3, 2016 at 18:24
  • 1
    Use the condition that is easier to read. Don't invert the condition just to avoid using an empty block ({}).
    – axiac
    Aug 3, 2016 at 18:27

6 Answers 6

16

You could do a negation instead:

if (! empty($data) && $data != 'unanswered') {
    echo $data;
}
2

This is legal in PHP and most other languages, but you can use the Boolean law DeMorgan's Law to shorten the if statement to this:

if(!empty($data) && $data != "unanswered"){
    echo $data;
}

DeMorgan's law just negates the Boolean expression.

1

It's valid to have empty curly brackets. However, from software engineering perspective it's very bad design. You better use DeMorgan's Law (you can see this in previous comments). It's better start learning how to write high quality code that can be understood by other developers.

1

This is a common problem. Empty brackets is quite ugly, but is allowed. For creating an effective and readable clause, use !(clause). Usage:

if( ! ( empty($data) || $data == "unanswered" ) )  {
    // do something
}
0

You should try reversing your conditional, so that your statements end up in the first set of curly brackets. With your statements in the first set of curly brackets, you can then omit the second set.

0

The answer to your question is yes you can do that. We do it sometimes when we visualize that we might come up with something to be put in there but only at later stage.

As many guys suggested you can negate the condition but it all depends on how do you visualize the future code.

Not the answer you're looking for? Browse other questions tagged or ask your own question.