title: How would you improve this form validation code?
body: <p>I need to validate a form. This is some server side validation that checks if required fields are filled out, emails are valid, numeric and alpha numeric fields don't contain rogue characters.</p>
  
  <p>I would like some feedback on how to improve the code to be more reliable and terse.</p>
  
  <pre><code>&lt;?php
  
  // current state
  $valid  = true;
  
  // post data collection
  $name   = "John Doe";
  $email  = "user@gmail.com";
  $age    = "19";
  
  // select data that needs validation
  $required   = array($name, $email);
  $validEmail     = array($email);
  $validNumber    = array($age);
  $validAlpha     = array($name);
  
  // check required fields
  for ($i=0; $i&lt;count($required); $i++) {
      if (strlen($required[$i]) == 0) {
          echo "Please fill out all required fields";
          $valid = false;
          break;
      }
  }
  
  // check for valid email field
  for ($i=0; $i&lt;count($validEmail); $i++) {
      if (preg_match('/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/', $validEmail[$i])) {
  
      } else {
          echo '"' . $validEmail[$i] . '"' . ' is an invalid email address &lt;br /&gt;';
          $valid = false;
      }
  }
  
  // check numeric fields
  for ($i=0; $i&lt;count($validNumber); $i++) {
      if (preg_match('/^[0-9 ]+$/', $validNumber[$i])) {
  
      } else {
          echo '"' . $validNumber[$i] . '"' . ' is an invalid number &lt;br /&gt;';
          $valid = false;
      }
  }
  
  // check alpha
  for ($i=0; $i&lt;count($validAlpha); $i++) {
      if (preg_match('/^[a-zA-Z ]+$/', $validAlpha[$i])) {
  
      } else {
          echo '"' . $validAlpha[$i] . '"' . ' contains invalid characters. This field only accepts letters. &lt;br /&gt;';
          $valid = false;
      }
  }
  
  // return "Your form was successfully sent"
  if ($valid) {
      echo 'Your form was successfully sent. &lt;br /&gt;Back to the site &lt;form&gt;&lt;input type="button" value="back" onclick="history.go(-1);return true;"&gt;&lt;/form&gt;';
  }
  
  ?&gt;
  </code></pre>