Edgar Edgar - 1 month ago 12
PHP Question

what do you recommend to clarify my understanding of my PHP code´s flow

when I use some nested if / else statements, sometimes I get confused if my code logic corresponds to my original idea. I use some simple procedural code, so how can I train my understanding?

Answer Source

Try to split your code up into functions. If you have deeply nested if/else statements then you can probably create well-named functions for both the "if" tests and the resulting logic. For example, change:

if ($something == "a" && $somethingElse == "b") {
    // code
else if ($whatever > 4) {
    // more code
else {
    // yet more code


if (condition1True()) {
else if (condition2True()) {
else {

Making your code read more like English means you can more easily understand how it works. You can also split your functionality so that each function only needs to do something simple then compose those functions into higher-level behaviour.

EDIT: Regarding comments, I tend to go for well-named functions and variables rather than copious commenting. If you can read the code without comments then that's ideal, but obviously you will still need comments sometimes. Definitely worth writing Javadoc-style comments for each function detailing the meanings of the arguments and return value, but inline comments in the code are sometimes more hindrance than help.