How to validate numeric value in php?

is_numeric() tests whether a value is a number. It doesn't necessarily have to be an integer though - it could a decimal number or a number in scientific notation.

The preg_match() example you've given only checks that a value contains the digits zero to nine; any number of them, and in any sequence.

Note that the regular expression you've given also isn't a perfect integer checker, the way you've written it. It doesn't allow for negatives; it does allow for a zero-length string (ie with no digits at all, which presumably shouldn't be valid?), and it allows the number to have any number of leading zeros, which again may not be the intended.

[EDIT]

As per your comment, a better regular expression might look like this:

/^[1-9][0-9]*$/

This forces the first digit to only be between 1 and 9, so you can't have leading zeros. It also forces it to be at least one digit long, so solves the zero-length string issue.

You're not worried about negatives, so that's not an issue.

You might want to restrict the number of digits, because as things stand, it will allow strings that are too big to be stored as integers. To restrict this, you would change the star into a length restriction like so:

/^[1-9][0-9]{0,15}$/

This would allow the string to be between 1 and 16 digits long (ie the first digit plus 0-15 further digits). Feel free to adjust the numbers in the curly braces to suit your own needs. If you want a fixed length string, then you only need to specify one number in the braces.

Hope that helps.

How to validate numeric value in php?

In this article, we will go over how to perform number, or numeric, validation of a form field filled in by a user, to make sure that the data entered is, in fact, a numeric value.

This may be necessary for a slew of forms filled out on the web. Examples of these are credit card numbers, zip codes, house numbers, telephone numbers, cash amounts, etc. These are all form fields where we want only numbers entered in to the form field. If any characters in the sequence are non-numeric, then we want to tell the user that the sequence of characters which they entered in are not valid. This is what is referred to as number validation.

Below is an example of a form field which checks for number validation. Only numbers can be entered in to the form field, only numeric values. If non-numeric values are entered, then the form field catches this and tells the user that s/he has made an error.

Result

Above is a form which checks for number validation. In this form, it is wanted that users enter numbers only into the form field. If a user enters a nonnumeric character, an error is thrown and the user is told to enter numbers only into the field.

PHP

So how do we perform number validation in PHP on a form field to make sure only numbers have been entered?

The answer is, we use a function in PHP called the is_numeric function.

The is_numeric function is used to check whether the character(s) which are entered. If all the characters are numeric, it returns a true value. If all the characters are not numeric, it returns a false, or not true, value.

Knowing now how this function works, we can implement it based on an if-else statement. If true, we can make it execute one statement. If false, we can make it execute another statement, such as the form above does.

HTML Code

This HTML code creates the text field in which a user enters characters.

The important thing we need to know from this HTML Code is the "name" attribute of the text field, which in this case is number. We will need to know this for the PHP code, because the "name" attribute is what we use in PHP of the HTML form field to test the characters that the user enters into this field.

PHP Code

(PHP 4, PHP 5, PHP 7, PHP 8)

is_numeric Finds whether a variable is a number or a numeric string

Description

is_numeric(mixed $value): bool

Parameters

value

The variable being evaluated.

Return Values

Returns true if value is a number or a numeric string, false otherwise.

Changelog

VersionDescription
8.0.0 Numeric strings ending with whitespace ("42 ") will now return true. Previously, false was return instead.

Examples

Example #1 is_numeric() examples

<?php
$tests 
= array(
    
"42",
    
1337,
    
0x539,
    
02471,
    
0b10100111001,
    
1337e0,
    
"0x539",
    
"02471",
    
"0b10100111001",
    
"1337e0",
    
"not numeric",
    array(),
    
9.1,
    
null,
    
'',
);

foreach (

$tests as $element) {
    if (
is_numeric($element)) {
        echo 
var_export($elementtrue) . " is numeric"PHP_EOL;
    } else {
        echo 
var_export($elementtrue) . " is NOT numeric"PHP_EOL;
    }
}
?>

The above example will output:

'42' is numeric
1337 is numeric
1337 is numeric
1337 is numeric
1337 is numeric
1337.0 is numeric
'0x539' is NOT numeric
'02471' is numeric
'0b10100111001' is NOT numeric
'1337e0' is numeric
'not numeric' is NOT numeric
array (
) is NOT numeric
9.1 is numeric
NULL is NOT numeric
'' is NOT numeric

Example #2 is_numeric() with whitespace

<?php
$tests 
= [
    
" 42",
    
"42 ",
    
"\u{A0}9001"// non-breaking space
    
"9001\u{A0}"// non-breaking space
];

foreach (

$tests as $element) {
    if (
is_numeric($element)) {
        echo 
var_export($elementtrue) . " is numeric"PHP_EOL;
    } else {
        echo 
var_export($elementtrue) . " is NOT numeric"PHP_EOL;
    }
}
?>

Output of the above example in PHP 8:

' 42' is numeric
'42 ' is numeric
' 9001' is NOT numeric
'9001 ' is NOT numeric

Output of the above example in PHP 7:

' 42' is numeric
'42 ' is NOT numeric
' 9001' is NOT numeric
'9001 ' is NOT numeric

See Also

  • Numeric strings
  • ctype_digit() - Check for numeric character(s)
  • is_bool() - Finds out whether a variable is a boolean
  • is_null() - Finds whether a variable is null
  • is_float() - Finds whether the type of a variable is float
  • is_int() - Find whether the type of a variable is integer
  • is_string() - Find whether the type of a variable is string
  • is_object() - Finds whether a variable is an object
  • is_array() - Finds whether a variable is an array
  • filter_var() - Filters a variable with a specified filter

sobolanx at gmail dot com

11 years ago

Note that the function accepts extremely big numbers and correctly evaluates them.

For example:

<?php
    $v
= is_numeric ('58635272821786587286382824657568871098287278276543219876543') ? true : false;var_dump ($v);
?>

The above script will output:

bool(true)

So this function is not intimidated by super-big numbers. I hope this helps someone.

PS: Also note that if you write is_numeric (45thg), this will generate a parse error (since the parameter is not enclosed between apostrophes or double quotes). Keep this in mind when you use this function.

moskalyuk at gmail dot com

16 years ago

is_numeric fails on the hex values greater than LONG_MAX, so having a large hex value parsed through is_numeric would result in FALSE being returned even though the value is a valid hex number

ben at chico dot com

8 years ago

Apparently NAN (Not A Number) is a number for the sake of is_numeric().

<?php
echo "is ";
if (!
is_numeric(NAN))
echo
"not ";
echo
"a number";
?>

Outputs "is a number". So something that is NOT a number (by defintion) is a number...

kouber at saparev dot com

18 years ago

Note that this function is not appropriate to check if "is_numeric" for very long strings. In fact, everything passed to this function is converted to long and then to a double. Anything greater than approximately 1.8e308 is too large for a double, so it becomes infinity, i.e. FALSE. What that means is that, for each string with more than 308 characters, is_numeric() will return FALSE, even if all chars are digits.

However, this behaviour is platform-specific.

http://www.php.net/manual/en/language.types.float.php

In such a case, it is suitable to use regular expressions:

function is_numeric_big($s=0) {
  return preg_match('/^-?\d+$/', $s);
}

Magnus Deininger, dma05 at web dot de

13 years ago

regarding the global vs. american numeral notations, it should be noted that at least in japanese, numbers aren't grouped with an extra symbol every three digits, but rather every four digits (for example 1,0000 instead of 10.000). also nadim's regexen are slightly suboptimal at one point having an unescaped '.' operator, and the whole thing could easily be combined into a single regex (speed and all).

adjustments:

<?php
$eng_or_world
= preg_match
 
('/^[+-]?'. // start marker and sign prefix
 
'(((([0-9]+)|([0-9]{1,4}(,[0-9]{3,4})+)))?(\\.[0-9])?([0-9]*)|'. // american
 
'((([0-9]+)|([0-9]{1,4}(\\.[0-9]{3,4})+)))?(,[0-9])?([0-9]*))'. // world
 
'(e[0-9]+)?'. // exponent
 
'$/', // end marker
 
$str) == 1;
?>

i'm sure this still isn't optimal, but it should also cover japanese-style numerals and it fixed a couple of other issues with the other regexen. it also allows for an exponent suffix, the pre-decimal digits are optional and it enforces using either grouped or ungrouped integer parts. should be easier to trim to your liking too.

How do I allow only numbers in PHP?

In PHP, for a "only numbers" validation you can use different approaches:.
is_int or is_integer..
is_numeric..
regular expressions..
ctype_digit..
filter_var..

What is not numeric in PHP?

The is_numeric() function is used to check whether a variable is numeric or not. *Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types. Return value: TRUE if var_name is a number or a numeric string, FALSE otherwise.

Is numeric array PHP?

Numeric arrays allow us to store multiple values of the same data type in a single variable without having to create separate variables for each value. These values can then be accessed using an index which in case of numeric arrays is always a number. Note: By default the index always starts at zero.

What is the use of Preg_match in PHP?

PHP | preg_match() Function. This function searches string for pattern, returns true if pattern exists, otherwise returns false. Usually search starts from beginning of subject string. The optional parameter offset is used to specify the position from where to start the search.