All posts by admin

Cleaning up PHP – Terminal conditions with continue;/return;

PHP (or any language where code blocks are indented) can get a bit messy sometimes

OK, that’s not a literal example, but it does happen. If your condition is terminal, that is: if it is not met, no further action is taken; then there is no need to wrap a massive chunk of code in curly braces and indent it yet further. Break out of the cycle! If you are in a loop, you can just continue; – for example instead of:

you can do this:

In this ridiculously abbreviated example, it does look longer, and yes it will always result in more code, but where you have several terminal conditions in a section of logic which are separated by a number of lines, this technique can save you one hell of a lot of indenting, making your code that much more readable. Our original example, while longer, would be a lot simpler to follow:

In a similar way to loops, if you are in a function, you can simply return; (or return true/false; as appropriate) earlier rather than doing it in an else statement; Shocking? No. A revelation? Hardly, these are not new constructs. But common? Not from the code I see. Give it a go. I will…