title: Checking that a value contains only digits, regex or no?
body: <p>I have a function that is used throughout my code. The function expects that the passed parameter is a positive integer. Since PHP is loosely typed, the data type is unimportant. But it <em>is</em> important that it contain nothing but digits. Currently, I am using a regular expression to check the value before continuing.</p>
  
  <p><strong>Here is a <em>simplified</em> version of my code:</strong></p>
  
  <pre><code>function do_something($company_id) {
      if (preg_match('/\D/', $company_id)) exit('Invalid parameter');
      //do several things that expect $company_id to be an integer
  }
  </code></pre>
  
  <p>I come from a Perl background and tend to reach for regular expressions often. However, I know their usage is controversial.</p>
  
  <p>I considered using <code>intval()</code> or <code>(int)</code> and <strong>forcing</strong> <code>$company_id</code> to be an integer. However, I could end up with some unexpected values and I want it to <em>fail fast</em>.</p>
  
  <p><strong>The other option is:</strong></p>
  
  <pre><code>if (!ctype_digit((string) $company_id)) exit('Invalid parameter');
  </code></pre>
  
  <p>Is this scenario a valid use of regular expressions? Is one way preferred over the other? If so, why? Are there any gotchas I haven't considered?</p>