Question

I know the performence difference will be very slight in both scenarios, but I was wondering which is a more practical, performance-improving version to write conditions in PHP.

if(condition){
  result;
}

VS

if(condition)
  result;
Was it helpful?

Solution

Both are exactly the same, it's coding style and has nothing to do with performance. Adapt the style you like better.

Some hint tools suggest to use the first style to avoid mistakes like this:

if(condition)
  result;
  foo; // Nothing to do with the condition but you can get confused.

While if you were using curly braces, this wouldn't have happen:

if(condition){
    result;
}
    foo; // Nothing to do with the condition but now it's clear.

I'm not using curly braces by the way for one statement in if, as this scenario isn't too difficult to avoid for non noobs.

OTHER TIPS

one line code doesnt require braces; but it is good practice of using braces for one line code too. both are the same.

Honestly, the difference would be insignificant, if any. I would always you {}, if for no other reason than formatting. I would be surprised if any system these days would have a significant difference.

There is no reason to even think about this kind of optimization. Whichever way you choose (depends on your personal preferred style), they will perform exactly the same.

they are the same from the result and performance point of view but you use

if(condition)
  result; 

only if you have one statement inside , if you have more you use parentheses

If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it.

The following example would display a is bigger than b if $a is bigger than $b:

<?php
if ($a > $b)
  echo "a is bigger than b";
?>

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:

<?php
if ($a > $b) {
  echo "a is bigger than b";
  $b = $a;
}
?>

If statements can be nested infinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.

for reference use php.net

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top