title: PHP - Avoiding nested if statements - cleaner way to code this
body: <p>Assume that I am creating a registration form.   I have code like the below and it is hard to manage because of all the nested if statements.</p>
  
  <p>I want to know the cleanest and easiest to follow way to write code that functions similarly to what I have below.</p>
  
  <p><strong>EDIT</strong>: People have told me that I can move the empty($_POST['email']) to the validation functions.   I can't do that because I need to know 1) whether user has posted data or not, and 2) whether the data user posted is valid.   </p>
  
  <p>For example, when the user first goes to the registration page, they have not posted any data so $_POST['email'] will generate PHP warnings because they don't exist.  That's why I check whether data has been posted before I validate.</p>
  
  <p>Does this make sense?</p>
  
  <pre><code>function validate_email($str) {
      $str = trim(strtolower($str));
      if(!filter_var($str, FILTER_VALIDATE_EMAIL)) {
        return false;
      } else {
        return $str;
      }
  }
  
  function validate_password($str) {
      $str = trim($str);
      if(strlen($str) &lt; 5 || strlen($str) &gt; 70) {
          return false;
      } else {
          return $str;
      }
  }
  
  $email = false;
  $password = false;
  $errorMessage = false;
  
  if(!empty($_POST['email'])) {
      $email = validate_email($_POST['email']);
      if($email) {
          if(!empty($_POST['password'])) {
              $password = validate_password($_POST['password']);
              if($password) {
                  createNewUser($email,$password);
              } else {
                  $errorMessage = "The password is not valid";
              }
          } else {
              $errorMessage = "The password is not valid";
          }
      } else {
          $errorMessage = "Email address is invalid";
      }
  } else {
      $errorMessage = "Email address is invalid";
  }
  
  if($errorMessage) echo $errorMessage;
  </code></pre>