Home > Web Development > Validating Integers

Validating Integers

December 9th, 2009

A while at work I came across some random reference where I need to validate that a $_POST or $_GET value was an integer. Now this is a fairy common problem, but like many PHP programmers I had never found Filter Var Functions. I came across what ended up being an extremely tedious work around.

The issue arises when a variable needs to be an integer where 0 is a possible value. Most databases don’t use 0 as indexs so this is a semi rare situation, but often happens on drop downs and sliders. The issue is as follows


$not_int = 'asdf';
$int        = '5';
$int_2    = 0;
is_int($not_int); //false

is_int($int);        //false(it's a string duh
is_int($int_2);     //true
intval($not_int);  // 0
intval($int)          // 5
intval($int_2);     // 0 

/* Then I had to figure out how to determine if the original value was 0;  Meaning if I passed in a 0, but it was a string My original theory was*/ 

if(intval($not_int) != $not_int) {}
/* This should've worked, btu upon further inspection i release with type converting for comparison i was essentially doing */ 

if(intval($not_int) != (int)$not_int){}  // Identical so they're always equal
$int        = '5';
$int_2    = 0;</div>
is_int($not_int); //false
is_int($int);        //false(it's a string duh
is_int($int_2);     //true
intval($not_int);  // 0
intval($int)          // 5
intval($int_2);     // 0
/* Then I had to figure out how to determine if the original value was 0;  Meaning if I passed in a 0, but it was a string My original theory was*/
if(intval($not_int) != $not_int) {}
/* This should've worked, btu upon further inspection i release with type converting for comparison i was essentially doing */
if(intval($not_int) != (int)$not_int){}  // Identical so they're always equal</div>

The solution is filter_var.

Filter var and it’s sister function sanitize var gives you a nice solution to this problem as well as many other problems in the web.

if(filter_var($not_int, FILTER_VALIDATE_INT) !== false ) {}

The tricky thing about this function is it returns the integer value, so be careful to use !== when comparing to false.
There are a large number of “filters” that can replace common used regexp, IP address, email, url. I’d suggest giving this a really good going over.

Logan Bailey Web Development

  1. No comments yet.
  1. No trackbacks yet.