PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
if (! STATEMENT 1){
exit;
}
if (! STATEMENT 2){
exit;
}
//EXECUTE CODE HERE
Is it better to code using a technique where you go deeper and deeper in the code following only if statement is met or is it better to do simple error check and just always stays "out" of the if statements?
I bet theres not much of a difference, but overall, which way should I choose?
Nested if .. else statements can be just as hard to debug as they can become unwieldy. Many times conditions can be combined or written differently to reduce the number of if .. else statements. Your first example could've been easily re-written as -
Further, if you're using any kind of abstraction (which you should) such as classes or functions, then I would advise returning early with simple error checking since it make the code more readable than nested if .. else statements.
I would also point out that using exit should be limited. It is essentially a goto and therefore defeats the organization of structured programming constructs like if's.
Just the other day I wrote some code like example one and today I read it and got lost and rewrote it as example 2.
Also today I had some code like example 2 that wasn't working exactly as I needed in all cases and the fix wound up looking like example 1.