Php check is number only

PHP: Checking if a variable contains only digits

For checking if a variable contains only digits, without the commas, periods, positive and negative signs, ctype_digit and preg_match are the functions you should use instead of is_numeric and is_int.

An array of numbers to verify, the first four should all evaulate to true and the last four should all evaluate to false.

$numbers = array( 987654321, 1234567890, "0987654321", "1234567890", -1, 2.2, 1e5, '1e3' );

bool ctype_digit(string $var), returns true if every character in the parameter is a decimal digit, false otherwise.

echo "cctype_digit \n"; foreach( $numbers as $n ) < if( ctype_digit($n) ) echo "true, digits only: $n \n"; else echo "false, NOT digits only: $n \n"; >echo "\n\n\n"; // cctype_digit // true, digits only: 987654321 // true, digits only: 1234567890 // true, digits only: 0987654321 // true, digits only: 1234567890 // false, NOT digits only: -1 // false, NOT digits only: 2.2 // false, NOT digits only: 100000 // false, NOT digits only: 1e3

int preg_match(string $pattern, string $var), returns 1 if the pattern matches the given string $var, 0 otherwise.

echo "preg_match \n"; foreach( $numbers as $n ) < if( preg_match('/^\d+$/',$n) ) echo "true, digits only: $n \n"; else echo "false, NOT digits only: $n \n"; >echo "\n\n\n"; // preg_match // true, digits only: 987654321 // true, digits only: 1234567890 // true, digits only: 0987654321 // true, digits only: 1234567890 // false, NOT digits only: -1 // false, NOT digits only: 2.2 // true, digits only: 100000 // false, NOT digits only: 1e3

bool is_numeric(mixed $var), returns true if the parameter $var is a number(including negative numbers, numbers with decimal places and numbers in scientific notations) or a numeric string, false otherwise.

echo "is_numeric \n"; foreach( $numbers as $n ) < if( is_numeric($n) ) echo "true, digits only: $n \n"; else echo "false, NOT digits only: $n \n"; >echo "\n\n\n"; // is_numeric // true, digits only: 987654321 // true, digits only: 1234567890 // true, digits only: 0987654321 // true, digits only: 1234567890 // true, digits only: -1 // true, digits only: 2.2 // true, digits only: 100000 // true, digits only: 1e3

bool is_int(mixed $var), returns ture if $var is an integer, false otherwise;

echo "is_int \n"; foreach( $numbers as $n ) < if( is_int($n) ) echo "true, digits only: $n \n"; else echo "false, NOT digits only: $n \n"; >echo "\n\n\n"; // is_int // true, digits only: 987654321 // true, digits only: 1234567890 // false, NOT digits only: 0987654321 // false, NOT digits only: 1234567890 // true, digits only: -1 // false, NOT digits only: 2.2 // false, NOT digits only: 100000 // false, NOT digits only: 1e3

Search within Codexpedia

Читайте также:  Scikit learn python sklearn

Источник

is_numeric

Determines if the given variable is a number or a numeric string.

Parameters

The variable being evaluated.

Return Values

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

Changelog

Version Description
8.0.0 Numeric strings ending with whitespace ( «42 » ) will now return true . Previously, false was returned instead.

Examples

Example #1 is_numeric() examples

$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 ( $element , true ) . » is numeric» , PHP_EOL ;
> else echo var_export ( $element , true ) . » 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

$tests = [
» 42″ ,
«42 » ,
«\u9001» , // non-breaking space
«9001\u» , // non-breaking space
];

foreach ( $tests as $element ) if ( is_numeric ( $element )) echo var_export ( $element , true ) . » is numeric» , PHP_EOL ;
> else echo var_export ( $element , true ) . » 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

User Contributed Notes 8 notes

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

$v = is_numeric ( ‘58635272821786587286382824657568871098287278276543219876543’ ) ? true : false ;

var_dump ( $v );
?>

The above script will output:

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.

for strings, it return true only if float number has a dot

is_numeric( ‘42.1’ )//true
is_numeric( ‘42,1’ )//false

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

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.

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

is incorrect for PHP8, it’s numeric.

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.

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

function is_numeric_big($s=0) return preg_match(‘/^-?\d+$/’, $s);
>

Note that is_numeric() will evaluate to false for number strings using decimal commas.

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).

$eng_or_world = preg_match
( ‘/^[+-]?’ . // start marker and sign prefix
‘((((1+)|(2(,4)+)))?(\\.7)?(1*)|’ . // american
‘(((3+)|(8(\\.4)+)))?(,1)?(3*))’ . // world
‘(e2+)?’ . // 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.

Источник

ctype_digit

Checks if all of the characters in the provided string , text , are numerical.

Parameters

Note:

If an int between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.

As of PHP 8.1.0, passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to string or an explicit call to chr() should be made.

Return Values

Returns true if every character in the string text is a decimal digit, false otherwise. When called with an empty string the result will always be false .

Examples

Example #1 A ctype_digit() example

$strings = array( ‘1820.20’ , ‘10002’ , ‘wsl!12’ );
foreach ( $strings as $testcase ) if ( ctype_digit ( $testcase )) echo «The string $testcase consists of all digits.\n» ;
> else echo «The string $testcase does not consist of all digits.\n» ;
>
>
?>

The above example will output:

The string 1820.20 does not consist of all digits. The string 10002 consists of all digits. The string wsl!12 does not consist of all digits.

Example #2 A ctype_digit() example comparing strings with integers

$numeric_string = ’42’ ;
$integer = 42 ;

ctype_digit ( $numeric_string ); // true
ctype_digit ( $integer ); // false (ASCII 42 is the * character)

is_numeric ( $numeric_string ); // true
is_numeric ( $integer ); // true
?>

See Also

  • ctype_alnum() — Check for alphanumeric character(s)
  • ctype_xdigit() — Check for character(s) representing a hexadecimal digit
  • is_numeric() — Finds whether a variable is a number or a numeric string
  • is_int() — Find whether the type of a variable is integer
  • is_string() — Find whether the type of a variable is string

User Contributed Notes 14 notes

All basic PHP functions which i tried returned unexpected results. I would just like to check whether some variable only contains numbers. For example: when i spread my script to the public i cannot require users to only use numbers as string or as integer. For those situation i wrote my own function which handles all inconveniences of other functions and which is not depending on regular expressions. Some people strongly believe that regular functions slow down your script.

The reason to write this function:
1. is_numeric() accepts values like: +0123.45e6 (but you would expect it would not)
2. is_int() does not accept HTML form fields (like: 123) because they are treated as strings (like: «123»).
3. ctype_digit() excepts all numbers to be strings (like: «123») and does not validate real integers (like: 123).
4. Probably some functions would parse a boolean (like: true or false) as 0 or 1 and validate it in that manner.

My function only accepts numbers regardless whether they are in string or in integer format.
/**
* Check input for existing only of digits (numbers)
* @author Tim Boormans
* @param $digit
* @return bool
*/
function is_digit ( $digit ) if( is_int ( $digit )) return true ;
> elseif( is_string ( $digit )) return ctype_digit ( $digit );
> else // booleans, floats and others
return false ;
>
>
?>

Please note that ctype_digit() will say true for strings such as ‘00001’, which are not technically valid representations of integers, while saying false to strings such as ‘-1’, which are. It’s basically a faster version of the regex /^\d+$/. As the name says, it answers the question «does this string contain only digits» literally. It does not answer «is this a valid representation of an integer». If that’s what you want, use is_int(filter_var($val, FILTER_VALIDATE_INT)) instead.

I just wanted to clarify a flaw in the function is_digit() suggested by «info at directwebsolutions dot nl » ..
It returns true in case of negative integers and false in case of strings that contain negative integers .
example:
is_digit(-10); // returns ture
is_digit(‘-10’); // returns false

Interesting to note that you must pass a STRING to this function, other values won’t be typecasted (I figured it would even though above explicitly says string $text).

$val = 42 ; //Answer to life
$x = ctype_digit ( $val );
?>

Will return false, even though, when typecasted to string, it would be true.

$val = ’42’ ;
$x = ctype_digit ( $val );
?>

Returns True.

$val = 42 ;
$x = ctype_digit ((string) $val );
?>

Which will also return true, as it should.

ctype_digit() will treat all passed integers below 256 as character-codes. It returns true for 48 through 57 (ASCII ‘0’-‘9’) and false for the rest.

ctype_digit(5) -> false
ctype_digit(48) -> true
ctype_digit(255) -> false
ctype_digit(256) -> true

(Note: the PHP type must be an int; if you pass strings it works as expected)

Источник

Оцените статью