PHP plays fast and loose with its data types which is one of the features that folks coming from more structured languages find very off-putting.
In phpland it's also the fastest way to sanitize an input which you expect to be an integer.
<?php $var = (int) $var;?>
The result is an integer. If the value of value of var is a number, it's converted into an integer. If it's not a number or doesn't begin with a number, then it's given a value of 0.
Here's a quick test script to illustrate the point. It tests both success and failure conditions.
And the results of this test when run with php 5.5?
Time to complete 1000000 (int) conversion filters:0.46194696426392
Time to complete 1000000 int_val filters:0.72814893722534
Time to complete 1000000 preg_replace filters:6.5657861232758
Time to complete 1000000 filter_var(x,FILTER_SANITIZE_NUMBER_INT) filters:1.5239408016205
The test does a million repetitions of numeric values and not-numeric values. The result being type cast is almost twice as fast as intval(), 3.7 times faster than filter_var() and 18x faster than preg_replace(). If we had not done this in a tight loop the results wouldn't have been so dramatic but you get the idea.
That's something to keep in the toolbox the next time you encounter an integer that needs to be filtered.
2 responses to “Cast to int is the fastest way to sanitize integer input”
How do you differentiate between a true 0 value (i.e. $var=0) and a 0 given by a failed cast (e.g. $var="rubbish") ?
In practice, this hasn't come up much.
Most of the time the int I'm working with is a primary key where zero isn't a possible value.
In a case where you want a zero value, intval() is your best option.