How can I check if form input is numeric in PHP? How can I check if form input is numeric in PHP? php php

How can I check if form input is numeric in PHP?


if(!is_numeric($quantity == 0)){                //redirect($data['referurl']."/badinput");                echo "is not numeric";

What you have here are two nested conditions.Let's say $quantity is 1.

The first condition evaluates 1 == 0 and returns FALSE.The second condition checks if FALSE is numeric and returns FALSE because FALSE is not numeric.

just write:

if (!is_numeric($quantity)){    echo 'is not numeric';}


You should probably explain what you mean by "numeric" - integral, floating point, exponential notation etc? is_numeric() will accept all of these.

If you want to check that a string contains nothing other than digits, then you could use a regular expression, e.g.

/^\d+$/

If you're going to use the actual value as if it were an integer, you'll probably want to pass it through intval() anyway, which will return 0 if the value cannot be parsed - if 0 is a valid value, then you'll probably have to handle that in some way, maybe by constraining the lower range of the value.


It might also be wise to do some client side validation of the input using JavaScript.

The round-trip to the server and back is a long one for what might amount to a typo, and you'll reduce server overhead by making the client browser do a bit of the quality assurance beforehand.