Php check type number

PHP is_numeric() Function

Check whether a variable is a number or a numeric string, or not:

$b = 0;
echo «b is » . is_numeric($b) . «
«;

$c = 32.5;
echo «c is » . is_numeric($c) . «
«;

$d = «32»;
echo «d is » . is_numeric($d) . «
«;

$e = true;
echo «e is » . is_numeric($e) . «
«;

$f = null;
echo «f is » . is_numeric($f) . «
«;
?>

Definition and Usage

The is_numeric() function checks whether a variable is a number or a numeric string.

This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.

Syntax

Parameter Values

Technical Details

Return Value: TRUE if variable is a number or a numeric string, FALSE otherwise
Return Type: Boolean
PHP Version: 4.0+

❮ PHP Variable Handling Reference

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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 ;
>
>
?>

Читайте также:  Https it tehnik ru software windows 10 disable serv win10 html

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

Читайте также:  Rest apis with django build powerful web apis with python and django

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

Источник

is_int

Finds whether the type of the given variable is integer.

Note:

To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric() .

Parameters

The variable being evaluated.

Return Values

Returns true if value is an int , false otherwise.

Examples

Example #1 is_int() example

$values = array( 23 , «23» , 23.5 , «23.5» , null , true , false );
foreach ( $values as $value ) echo «is_int(» ;
var_export ( $value );
echo «) color: #007700″>;
var_dump ( is_int ( $value ));
>
?>

The above example will output:

is_int(23) = bool(true) is_int('23') = bool(false) is_int(23.5) = bool(false) is_int('23.5') = bool(false) is_int(NULL) = bool(false) is_int(true) = bool(false) is_int(false) = bool(false)

See Also

  • is_bool() — Finds out whether a variable is a boolean
  • is_float() — Finds whether the type of a variable is float
  • is_numeric() — Finds whether a variable is a number or a numeric string
  • is_string() — Find whether the type of a variable is string
  • is_array() — Finds whether a variable is an array
  • is_object() — Finds whether a variable is an object

User Contributed Notes 30 notes

I’ve found that both that is_int and ctype_digit don’t behave quite as I’d expect, so I made a simple function called isInteger which does. I hope somebody finds it useful.

function isInteger ( $input ) return( ctype_digit ( strval ( $input )));
>

var_dump ( is_int ( 23 )); //bool(true)
var_dump ( is_int ( «23» )); //bool(false)
var_dump ( is_int ( 23.5 )); //bool(false)
var_dump ( is_int ( NULL )); //bool(false)
var_dump ( is_int ( «» )); //bool(false)

var_dump ( ctype_digit ( 23 )); //bool(true)
var_dump ( ctype_digit ( «23» )); //bool(false)
var_dump ( ctype_digit ( 23.5 )); //bool(false)
var_dump ( ctype_digit ( NULL )); //bool(false)
var_dump ( ctype_digit ( «» )); //bool(true)

var_dump ( isInteger ( 23 )); //bool(true)
var_dump ( isInteger ( «23» )); //bool(true)
var_dump ( isInteger ( 23.5 )); //bool(false)
var_dump ( isInteger ( NULL )); //bool(false)
var_dump ( isInteger ( «» )); //bool(false)
?>

Keep in mind that is_int() operates in signed fashion, not unsigned, and is limited to the word size of the environment php is running in.

is_int ( 2147483647 ); // true
is_int ( 2147483648 ); // false
is_int ( 9223372036854775807 ); // false
is_int ( 9223372036854775808 ); // false
?>

In a 64-bit environment:

is_int ( 2147483647 ); // true
is_int ( 2147483648 ); // true
is_int ( 9223372036854775807 ); // true
is_int ( 9223372036854775808 ); // false
?>

If you find yourself deployed in a 32-bit environment where you are required to deal with numeric confirmation of integers (and integers only) potentially breaching the 32-bit span, you can combine is_int() with is_float() to guarantee a cover of the full, signed 64-bit span:

Читайте также:  Java convert entity to dto

$small = 2147483647 ; // will always be true for is_int(), but never for is_float()
$big = 9223372036854775807 ; // will only be true for is_int() in a 64-bit environment

if( is_int ( $small ) || is_float ( $small ) ); // passes in a 32-bit environment
if( is_int ( $big ) || is_float ( $big ) ); // passes in a 32-bit environment
?>

Simon Neaves was close on explaining why his function is perfect choice for testing for an int (as possibly most people would need). He made some errors on his ctype_digit() output though — possibly a typo, or maybe a bug in his version of PHP at the time.

The correct output for parts of his examples should be:

var_dump ( ctype_digit ( 23 )); //bool(false)
var_dump ( ctype_digit ( «23» )); //bool(true)
var_dump ( ctype_digit ( 23.5 )); //bool(false)
var_dump ( ctype_digit ( NULL )); //bool(false)
var_dump ( ctype_digit ( «» )); //bool(false)
?>

As you can see, the reason why using *just* ctype_digit() may not always work is because it only returns TRUE when given a string as input — given a number value and it returns FALSE (which may be unexpected).

With this function you can check if every of multiple variables are int. This is a little more comfortable than writing ‘is_int’ for every variable you’ve got.

function are_int ( ) $args = func_get_args ();
foreach ( $args as $arg )
if ( ! is_int ( $arg ) )
return false ;
return true ;
>

// Example:
are_int ( 4 , 9 ); // true
are_int ( 22 , 08, ‘foo’ ); // false
?>

Источник

is_numeric

Проверяет, является ли данная переменная числом. Строки, содержащие числа, состоят из необязательного знака, любого количества цифр, необязательной десятичной части и необязательной экспоненциальной части. Так, +0123.45e6 является верным числовым значением. Шестнадцатеричная (0xFF), двоичная (0b10100111001) и восьмеричная (0777) записи также допускаются, но только без знака, десятичной и экспоненциальной части.

Список параметров

Возвращаемые значения

Возвращает TRUE , если var является числом или строкой, содержащей число, в противном случае возвращается FALSE .

Примеры

Пример #1 Примеры использования is_numeric()

$tests = array(
«42» ,
1337 ,
0x539 ,
02471 ,
0b10100111001 ,
1337e0 ,
«not numeric» ,
array(),
9.1
);

foreach ( $tests as $element ) if ( is_numeric ( $element )) echo «‘ < $element >‘ — число» , PHP_EOL ;
> else echo «‘ < $element >‘ — НЕ число» , PHP_EOL ;
>
>
?>

Результат выполнения данного примера:

'42' - число '1337' - число '1337' - число '1337' - число '1337' - число '1337' - число 'not numeric' - НЕ число 'Array' - НЕ число '9.1' - число

Смотрите также

  • ctype_digit() — Проверяет на наличие цифровых символов в строке
  • is_bool() — Проверяет, является ли переменная булевой
  • is_null() — Проверяет, является ли значение переменной равным NULL
  • is_float() — Проверяет, является ли переменная числом с плавающей точкой
  • is_int() — Проверяет, является ли переменная переменной целочисленного типа
  • is_string() — Проверяет, является ли переменная строкой
  • is_object() — Проверяет, является ли переменная объектом
  • is_array() — Определяет, является ли переменная массивом

Источник

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