Do-while instead of if-else
I've been examining some PHP code today and I've not开发者_运维技巧iced the usage of do-while with breaks instead of if-else. What are the advantages of it? Code readability? Speed? Anything else?
I assume you mean this:
do {
...
if ($foo == $bar) break;
...
} while (false);
It is just a way to skip over a piece of code without the nesting normal if statements would involve. The break statement is used as a goto statement, to go to the end of the while loop. The whole piece is wrapped in a do-while-false loop so that it gets executed once and allows break statements.
do/while loops guaranteed that the body of the do/while is executed at least once, after which the loop condition is checked.
On the flip side, if
guarantees that the code will not execute at all if the condition fails.
Internally there's no difference to them, except for the point at which the loop's conditionals are checked.
if/else is more suited for checking for one or more logical conditions with no need for looping or recursion -
do/while is more suited for iterating over data or groups of data until a desired result is reached.
if you're going to be using break statements, it depends on if you're going to need to recursively perform an action - otherwise if/else may be better suited.
精彩评论