eggfriedrice.com

PHP Number Validation

August 10th, 2007

I have nothing of any use or consequence to blog about today, I did some work, we went to Sainsbury’s, that’s about it really. Instead I’ll post a little PHP trick I’ve discovered.

It’s a very simple one-liner to test if a number is actually a number, it validates this without needing a special class, it just uses built in PHP functions. This is kind of validation is very important if you’re about to poke that number into a database query to, for example, pull out a page based on it’s ID.

This is it:
if($id != strval(intval($id))){
echo("Invalid ID");
die();
}

Variables in PHP are loosely typed so they can hold anything without the programmer specifying what they should be allowed to hold. This means that $id could hold an integer number or a floating point number or a string or an object or any number of other things. What we do here is use intval() and strval() to firstly get the integer value of $id and then turn it back into a string then compare it to itself. The net effect is that if $id holds a 2 intval() will return 2, strval() will then return the string “2″ and that’s the original value (the value in $id was actually a string to start with).

If you put in, say “cheese” then intval() would return a 0. It won’t work without strval() as it is needed to handle the weird values intval() returns (that I don’t fully understand).

All the code does is check that the number is an integer and if not print a message and exit. It won’t catch non-existent database records for example but as a simple, first pass, test it’s quite handy.

Comments

  1. 1

    i want to learn number validation

    - srinivasan @

Leave a Reply