Home > Tutorials > PHP > PHP Tip #2: Is_Numeric() Is A Very Useful Thing
Permalink to PHP Tip #2: Is_Numeric() Is A Very Useful Thing

PHP Tip #2: Is_Numeric() Is A Very Useful Thing

by on 03.13.2009 | 4 comments

The second in my series of PHP tips is to do with the extremely handy is_numeric(). When allowing user input it’s extremely important to check [...]

The second in my series of PHP tips is to do with the extremely handy is_numeric(). When allowing user input it’s extremely important to check the input for attacks. The most common piece of information handed to MySQL is an ID, but novice coders can get confused with how to check the input. The main problem is that you only want a number, but you can’t check for an integer since it will be a string. That’s where is_numeric() comes to the rescue. Just check to see if the user input is_numeric() & if it is do whatever you want. If we need an integer instead of a string we can use type casting. Here’s an example:

//$_GET['input'] is equal to the string 3.
if(is_numeric($_GET['input'])) {
  (int) $_GET['input'] = $input;
} else {
  //Something to run if input is not valid.
}

Simplez. :D

Another Way To Do It

Daniel in a comment below has offered another way to write a similar thing showing the diversity of PHP. :)

if ( ! 0 < ( $input = (int) $_GET['input'] ) ) {
  // something to run if input is not valid
}

I would however prefer to use something like this:

if ( ! 0 > ( $input = (int) $_GET['input'] ) ) {
  // something to run if input is not valid
} else {
  //something to run if successful
}

Since a string converted to an integer will always produce 0 that will detect invalid input without using is_numeric() for the most part anyway. Just bare in mind it will also mark 0 as invalid.

Written by Paul Robinson

A Web coder in languages such as CSS, X/HTML, jQuery, but mostly PHP. Addicted to Girls Aloud, Jennifer Morrison, Carah Faye Charnow, TV Show Chuck, and completely in love with Yvonne Strahovski's smile.

Give something back!

If you LOVED this tutorial and would like to show your appreciation, please consider or a little something from our Amazon Wishlist.

Discussion: 4 Comments

  1. Mar 13th, 2009 @ 20:20:53

    Hi,

    I would prefer it this way:

    if ( ! 0 < ( $input = (int) $_GET['input'] ) ) {
    // something to run if input is not valid
    }

    But there are many ways ^^


  2. Mar 13th, 2009 @ 20:22:54

    Of course. That’s the great thing about PHP there are so many different ways to write the same thing it’s nearly impossible not to find a version that suits the application you are writing. :)

    I might add your version to the post if you don’t mind. ;)


  3. Mar 15th, 2009 @ 13:45:01

    No, thanks, I don’t mind ;)


  4. Mar 15th, 2009 @ 13:47:55

    Thanks. :)


Leave a comment

Please enclose code in [lang] tags. For example [php] echo 'hello world'; [/php]

* Name, Email, Comment are Required