redconservatory
redconservatory

Reputation: 21934

Php: what's the difference between while...endwhile; and while { // stuff here }

What's the difference between

while (expression):

// do stuff

endwhile;

and

while {

}

Upvotes: 26

Views: 39192

Answers (4)

Brandon Lee
Brandon Lee

Reputation: 41

The difference is negligible when the code is actually run, but when coding I find that typing the brackets is (1): quicker, (2): more conventional, and (3): allows for less chance of error (endwhle anyone?).

As a bonus, the editor I use auto-formats the while loops (with brackets, by default) and down the road, if anything is off, the built-in bracket-matching function will catch it.

Upvotes: 3

Jon
Jon

Reputation: 437654

There's no real difference when writing code.

There can be a difference in levels of convenience in very special circumstances. For example, suppose you are writing a template engine that converts template code to native PHP code which is then cached and executed directly for speed.

In this case, the fact that while...endwhile; avoids using braces may allow you to simplify your parsing algorithm if e.g. it recognizes variables that should be substituted with a syntax like {$var}, which also uses braces.

Of course this is a pretty small benefit in a really extraordinary situation, but you take what you can. :)

Upvotes: 2

Jeff Davis
Jeff Davis

Reputation: 4797

There is no functional difference.

In practical use I find that:

while (expression):
// do stuff
endwhile;

Is more readable for the designers when you are embedding php code within html. IE:

<? while ($cssClass = array_pop($array)): ?>
   <li class="<?=$cssClass?>">
<? endwhile; ?>

Whereas:

while {

}

Is more readable within a php code block.

Upvotes: 46

S M
S M

Reputation: 8165

There's no difference, it comes down to personal preference.

Upvotes: 7

Related Questions