PHP 8.3.4 Released!

is_numeric

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

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

Описание

is_numeric(mixed $value): bool

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

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

value

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

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

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

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

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

Примеры

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

<?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($element, true) . " число", PHP_EOL;
} else {
echo
var_export($element, true) . " НЕ число", PHP_EOL;
}
}

?>

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

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

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

<?php

$tests
= [
" 42",
"42 ",
"\u{A0}9001", // Неразрывный пробел
"9001\u{A0}", // Неразрывный пробел
];
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() - Фильтрует переменную с помощью определённого фильтра

add a note

User Contributed Notes 8 notes

up
93
sobolanx at gmail dot com
13 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.
up
32
tanguy_barsik at hotmail dot com
7 years ago
for strings, it return true only if float number has a dot

is_numeric( '42.1' )//true
is_numeric( '42,1' )//false
up
12
moskalyuk at gmail dot com
17 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
up
9
ben at chico dot com
10 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...
up
3
Magnus Deininger, dma05 at web dot de
15 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.
up
3
kouber at saparev dot com
20 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);
}
up
2
Katrina Kizenbach
1 year ago
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
up
-6
anantkumarsingh03101988 at gmail dot com
1 year ago
Example #2

Output:

'9001 ' is NOT numeric

is incorrect for PHP8, it's numeric.

So please correct this.
To Top