PHP - Nested IF statements

Nesting too deeply is generally a bad idea - it's spaghetti logic and difficult to follow. Since each of your verification steps depends on the previous stage having succeeded, don't nest at all - just bail out when a stage fails:

function change_password(blah blah blah) {
   if (!$condition1) {
      return false;
   }
   if (!$condition2) {
      return false;
   }
   etc....


   // got here, must have succeeded
   return true;
}

That makes it explicitly clear what the logic sequence is.


I think it is definitely well readable and can easily be understood in comparison to using just one if statement like

if (blah and blah and blah and blah and blah and blah and blah) {}

However I'd still prefer doing it this way - too much indention can get kinda annoying:

function change_password($email, $password, $new_password, $confirm_new_password)
{
    if (!$email || !$password || !$new_password || !$confirm_new_password) return false;
    if ($new_password != $confirm_new_password) return false;
    if (!login($email, $password)) return false;
    if (!set_password($email, $new_password)) return false;

    return true;
}

Tags:

Php

Nested If