0

So I have an if-statement and I am not sure how is the best way to write it. Or if there is a proper way of writing it. Can I just use && every time or should I separate them with more () or does it really matter, is there a difference in performance ect?

$a = 10;
$b = 20;
$c = 8;
$d = 25;
$e = "";
$f = "not blank";

// FIRST EXAMPLE
if (!empty($e) && !empty($f) && $a <= $c && $b <= $d)
{
    // do something here
}

OR

if ( (!empty($e) && !empty($f)) && ($a <= $c && $b <= $d))
{
    // do something here
}
1
  • 2
    If all your conditions are AND, then there's no need for brackets at all. If you have some OR conditions combined with AND conditions, you'll likely need some brackets. Commented Dec 4, 2016 at 16:24

3 Answers 3

1

Generally whether you need to use brackets depends on the precedence of the operators you are using in the condition of the if statement. See the official PHP documentation on it for more detail.

Personally, in the case of if statements (and code in general within reason) I favour readability above all.

For instance, with the following if statement you suggested:

if (!empty($e) && !empty($f) && $a <= $c && $b <= $d)
{
    // do something here
}

For someone who is not familiar with the code, it can initially take a bit longer to see what's happening. There are many ways to combat this. One example is splitting the condition into separate if statements and maybe throwing exceptions if it fits in with your logic. In this case your example could become something like this:

if (empty($e) || empty($f))
{
    // throw exception as one or both of $e or $f is empty
}

if ($a <= $c && $b <= $d)
{
    // do something here
}

The example may not be logically correct but hopefully it helps in throwing a different perspective on things.

Sign up to request clarification or add additional context in comments.

Comments

0

It only depends of your needs. Don't use brackets when you don't need it. It making code harder to read. In your case you shouldn't use brackets, just:

if ( !empty($e) && !empty($f) && $a <= $c && $b <= $d)
{
    // do something here
}

In this case there is completely no need to use more brackets because you have only &&. As it comes to performance, less brackets - less work for interpreter.

2 Comments

So as Qirel pointed out above only use extra brackets for && while using || with it?
Yes, if you are using || in most cases you will need brackets. Just like in maths (2+2)*2 - brackets are executing first.
0

You need to keep each statement in different brackets

if ( (!empty($e) && (!empty($f) && ($a <= $c) && ($b <= $d))
{
 // do something here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.