title: Fastest PHP Type Jugling with settype() vs *val() functions?
body: <p>I am trying to figure out the fastest way (in PHP 5) to check that a value is the <a href="http://us2.php.net/manual/en/language.types.type-juggling.php" rel="nofollow noreferrer">type I need</a> it to be. I created two lines of code which both do the same thing. The problem is that I can't figure out which is fastest based off of benchmarks.</p>
  
  <pre><code>(is_scalar($value) ? intval($value) : 0);
  settype($value, 'integer');
  </code></pre>
  
  <p>I created the following test code but I don't have any more than my own PC (Core2Quad + XP 32bit + php5.2.5) and a dreamhost account to test it with - both of which show about the same times for this code.</p>
  
  <pre><code>$array = array(
      'false' =&gt; FALSE,
      'false2'=&gt; 0,
      'false3'=&gt; '0',
      'false4'=&gt; 'FALSE',
      'true'  =&gt; TRUE,
      'true2' =&gt; 1,
      'true3' =&gt; '1',
      'true4' =&gt; 'TRUE',
  
      'char'  =&gt; chr(250),
      'char2' =&gt; chr(10),
      'utf'   =&gt; 0xF0,
      'utf1'  =&gt; 0xFE,
  
      'number' =&gt; '452.5435',
      'number2' =&gt; '-3948.33e2',
      'number3' =&gt; -343.54,
      'number4' =&gt; 99.999,
      'number5' =&gt; '3jk439fjk23945t324098523.349fj324r',
  
      'int'   =&gt; 2323,
      'int2'  =&gt; '2345',
      'int3'  =&gt; '0',
      'int4'  =&gt; array(),
      'int5'  =&gt; '39582347823908270983249078530793249802357846t890234879023490785',
      'int6'  =&gt; 3895732890543789324890123467548093248976123890548793289073246789458901234,
  
      'object3' =&gt; new SimpleXMLElement('&lt;xml&gt;&lt;/xml&gt;'),
  
      'array' =&gt; array(),
      'array2' =&gt; array('hello'),
      'array3' =&gt; array(3,54,21,0),
      'array4' =&gt; array(0.2)
  );
  
  
  $start = microtime(TRUE);
  
  for($x=0;$x&lt;10000;$x++) {
      foreach( $array as $value ) {
          (is_scalar($value) ? intval($value) : 0);
          //settype($value, 'integer');
      }
  }
  
  print (microtime(TRUE) - $start). ' seconds';
  </code></pre>
  
  <p>Anyway, I was wondering if there might be more here that I am missing as to which of these methods might not only work faster - but might yield odd results as well. Another thing is that should this prove success full with ints - then other types such as strings and floats should also work.</p>
  
  <p>:UPDATE:</p>
  
  <p>I just tested these methods against the float type and found that settype() was slower (.28 sec) vs floatval() (.21 sec). So the answer to this question may only be valid for the int type.</p>
  
  <pre><code>//Float
  (is_scalar($value) ? floatval($value) : 0);
  settype($value, 'float');
  </code></pre>