is_numeric

(PHP 4, PHP 5, PHP 7)

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

Описание

bool is_numeric ( mixed $var )

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

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

var

Проверяемая переменная.

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

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

Примеры

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

<?php
$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() - Определяет, является ли переменная массивом

Коментарии

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.

language.types.float

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

function is_numeric_big($s=0) {
  return preg_match('/^-?\d+$/', $s);
}
2003-11-24 05:05:11
http://php5.kiev.ua/manual/ru/function.is-numeric.html
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
2006-08-21 13:18:16
http://php5.kiev.ua/manual/ru/function.is-numeric.html
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.
2009-01-07 08:01:40
http://php5.kiev.ua/manual/ru/function.is-numeric.html
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.
2011-01-22 17:55:26
http://php5.kiev.ua/manual/ru/function.is-numeric.html
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...
2014-01-08 01:20:43
http://php5.kiev.ua/manual/ru/function.is-numeric.html
for strings, it return true only if float number has a dot

is_numeric( '42.1' )//true
is_numeric( '42,1' )//false
2017-02-03 17:22:09
http://php5.kiev.ua/manual/ru/function.is-numeric.html
Example #2

Output: 

'9001 ' is NOT numeric

is incorrect for PHP8, it's numeric.

So please correct this.
2022-08-22 08:16:50
http://php5.kiev.ua/manual/ru/function.is-numeric.html
Автор:
Note that is_numeric() will evaluate to false for number strings using decimal commas.

is_numeric('0.11');
Output: true

is_numeric('0,11');
Output: false
2022-12-07 10:44:55
http://php5.kiev.ua/manual/ru/function.is-numeric.html

    Поддержать сайт на родительском проекте КГБ