Php: Best Way to Check If Input Is a Valid Number

PHP: Best way to check if input is a valid number?

ctype_digit was built precisely for this purpose.

Check if user enters numbers ONLY, PHP

First of all, you could disallow the person to enter anything but numbers in the <input../> by defining it's type as type="number".

Obviously, people could go around it so you still need to check it in the backend for that, you'll need to use a function like is_numeric().

PHP: Validate a given string is a valid number

You could use this function:

function hasNumericFormat($str) {
return preg_match("/^[-+]?[$]?([1-9]\d{0,2}(,\d{3})*|0)(\.\d+)?$/", $str);
}

Test code:

function test($str) {
if (hasNumericFormat($str)) {
echo "$str is OK<br>";
} else {
echo "$str violates numerical format<br>";
}
}

test("-$1,234,567.89"); // ok
test(",123,567.89"); // not ok: digit missing before comma
test("1,123,56"); // not ok: not 3 digits in last group
test("-0,123,567"); // not ok: first digit is zero
test("+0"); // ok

See it run on eval.in

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';
}

PHP form check if user inputs the correct number

simple "if"

if ($_POST['number'] == 200){
// OK do something
} else {
// not 200
}

Best way to check for positive integer (PHP)?

the difference between your two code snippets is that is_numeric($i) also returns true if $i is a numeric string, but is_int($i) only returns true if $i is an integer and not if $i is an integer string. That is why you should use the first code snippet if you also want to return true if $i is an integer string (e.g. if $i == "19" and not $i == 19).

See these references for more information:

php is_numeric function

php is_int function

Check if variable is a number and positive integer in PHP?

To check if a string input is a positive integer, i always use the function ctype_digit. This is much easier to understand and faster than a regular expression.

if (isset($_GET['p']) && ctype_digit($_GET['p']))
{
// the get input contains a positive number and is safe
}


Related Topics



Leave a reply



Submit