cahnory

Test if a var is INT or "INT STRING"

Jul 4th, 2011
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.96 KB | None | 0 0
  1. <?php
  2.  
  3.     $tests = array(
  4.         '1', 1, '1.4', 1.4, 'a', '1e4', array()
  5.     );
  6.    
  7.     foreach($tests as $test) {
  8.         var_dump(
  9.             $test,
  10.             (bool)preg_match('#^[0-9]+$#', $test),
  11.             is_numeric($test) && $test == (int)$test
  12.             );
  13.         echo "\r\n";
  14.     }
  15.    
  16.     $start  =   microtime();
  17.     for($i=0; $i < 100;$i++) {
  18.         foreach($tests as $test) {
  19.             is_numeric($test) && $test == (int)$test;
  20.         }
  21.     }
  22.     echo microtime() - $start."\r\n";
  23.    
  24.     $start  =   microtime();
  25.     for($i=0; $i < 100;$i++) {
  26.         foreach($tests as $test) {
  27.             preg_match('#^[0-9]+$#', $test);
  28.         }
  29.     }
  30.     echo microtime() - $start."\r\n";
  31.    
  32.     /*
  33.         string(1) "1"
  34.         bool(true)
  35.         bool(true)
  36.        
  37.         int(1)
  38.         bool(true)
  39.         bool(true)
  40.        
  41.         string(3) "1.4"
  42.         bool(false)
  43.         bool(false)
  44.        
  45.         float(1.4)
  46.         bool(false)
  47.         bool(false)
  48.        
  49.         string(1) "a"
  50.         bool(false)
  51.         bool(false)
  52.        
  53.         string(3) "1e4"
  54.         bool(false)
  55.         bool(false)
  56.        
  57.         array(0) {
  58.         }
  59.         bool(false)
  60.         bool(false)
  61.        
  62.         0.00048
  63.         0.053274
  64.     */
  65.  
  66. ?>
Advertisement
Add Comment
Please, Sign In to add comment