PHP & Web Development :: PHP Performance + Benchmarking :: Testing Numeric Variables

Testing Numeric Variables

BulletWhen validating numeric user input, I usually use the PHP function is_numeric(). Often though, I am really looking for an integer and not merely a numeric value. Below is the performance test of is_numeric() and is_int().

Test Environment: Linux, Apache, PHP 4.3.11 with PHP loaded using FastCGI. Zend Optimizer 2.5.7 installed. What's Zend Optimizer?

Test Setup: Code constructs listed below. For loops used to have enough iterations to make the script execution time calculatable.

Refresh the page to execute a new trial!

Comparisons
Bulletis_numeric()
  • Execution time: 4.99 ms
  • Average: 7.60 ms over 970 trials
Bulletis_int()
  • Execution time: 7.12 ms
  • Average: 7.94 ms over 970 trials
Results
Test Avg Execution Time Comparative Graph - (longer is slower, 100% is the fastest time)
is_numeric() 7.60 ms Performance Graph 100%
is_int() 7.94 ms Performance Graph 104%

Discussion: The two functions are close enough in execution time to not warrant any thought about performance when validating input. Though we often know whether a value is an integer, using is_int() can be tricky. When validating data, often you have strings that are like "23233." This numeric string would equal true in the is_numeric(), but is_int() would return false because it does not attempt to cast the input into an int when evaluating. Having to remember to cast your variable to an int before running is_int() is also troublesome, because if the variable was equal to 2.3, casting to an integer would now make it equal to 2 and it would now pass our is_int() test even though the original user input clearly wasn't an integer.