Проверка на числовое значение php

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

Определяет, является ли данная переменная числом или строкой, содержащей число.

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

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

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

Список изменений

Версия Описание
8.0.0 Строки, состоящие из чисел, заканчивающиеся пробелом ( «42 » ), теперь будут возвращать true . Ранее вместо этого возвращалось false .

Примеры

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

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

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

42 - число 1337 - число 1337 - число 1337 - число 1337 - число 1337.0 - число '0x539' - НЕ число '02471' - число '0b10100111001' - НЕ число '1337e0' - число 'not numeric' - НЕ число array ( ) - НЕ число 9.1 - число NULL - НЕ число '' - НЕ число

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

$tests = [
» 42″ ,
«42 » ,
«\u9001» , // неразрывный пробел
«9001\u» , // неразрывный пробел
];
foreach ( $tests as $element ) if ( is_numeric ( $element )) echo var_export ( $element , true ) . » — число» , PHP_EOL ;
> else echo var_export ( $element , true ) . » — НЕ число» , PHP_EOL ;
>
>
?>

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

' 42' - число '42 ' - число ' 9001' - НЕ число '9001 ' - НЕ число

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

' 42' - число '42 ' - НЕ число ' 9001' - НЕ число '9001 ' - НЕ число

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

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

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
‘((((6+)|(3(,8)+)))?(\\.3)?(8*)|’ . // american
‘(((2+)|(4(\\.5)+)))?(,1)?(3*))’ . // world
‘(e8+)?’ . // 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_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() — Определяет, является ли переменная массивом

Источник

is_int

Замечание:

Чтобы проверить, что переменная является числом или строкой, содержащей число (как поле ввода в форме, которое всегда является строкой), используйте is_numeric() .

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

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

Возвращает true , если value является целым числом ( int ), или false в противном случае.

Примеры

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

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

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

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)

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

  • is_bool() — Проверяет, является ли переменная булевой
  • is_float() — Проверяет, является ли переменная числом с плавающей точкой
  • is_numeric() — Проверяет, является ли переменная числом или строкой, содержащей число
  • is_string() — Проверяет, является ли переменная строкой
  • is_array() — Определяет, является ли переменная массивом
  • is_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:

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

Источник

Читайте также:  Проверка логина пароля html
Оцените статью