Hướng dẫn is_numeric in php

1. Chức năng của hàm is_numeric()

Hàm is_numeric() trong PHP có chức năng kiểm tra một biến có phải là một số hoặc một chuỗi gồm các chữ số hay không.

2. Cú pháp của hàm is_numeric()

is_numeric(mixed $value): bool

Trong đó:

  • $value là biến cần kiểm tra có phải là một số hoặc một chuỗi gồm các chữ số hay không. Biến này khi truyền vào cho hàm is_numeric() thì có thể là bất kỳ kiểu dữ liệu nào.
  • Kiểu dữ liệu trả về là bool. Nếu $valuemột số hoặc một chuỗi gồm các chữ số thì trả về true, nếu không thì trả về false.

3. Một số ví dụ sử dụng hàm is_numeric()


Kết quả

is_numeric('42') = bool(true)
is_numeric(' 7.8') = bool(true)
is_numeric(' 1ab') = bool(false)
is_numeric(1337) = bool(true)
is_numeric(1337) = bool(true)
is_numeric(1337) = bool(true)
is_numeric(1337) = bool(true)
is_numeric(1337.0) = bool(true)
is_numeric('0x539') = bool(false)
is_numeric('02471') = bool(true)
is_numeric('0b10100111001') = bool(false)
is_numeric('1337e0') = bool(true)
is_numeric('not numeric') = bool(false)
is_numeric(array ( 0 => '1', 1 => 2, )) = bool(false)
is_numeric(9.1) = bool(true)
is_numeric(NULL) = bool(false)
is_numeric('') = bool(false)
is_numeric(true) = bool(false)
is_numeric(false) = bool(false)

Các bạn cần cần lưu ý một số cách viết khác của số như:

    • 0x539 là số 1337 được biểu diễn dưới hệ cơ số 16
    • 02471 là số 1337 được biểu diễn dưới hệ cơ số 8
    • 0b10100111001 là số 1337 được biểu diễn dưới hệ nhị phân
    • 1337e0 tương đương 1337.100 (một ký hiệu của lũy thừa trong toán học)

Các bạn có thể tham khảo thêm quy ước numberic string trong PHP.

  • Đặc điểm của các phương pháp lập trình
  • Cấu trúc rẽ nhánh if…else trong PHP
  • Các loại Thread trong Java: Daemon Thread và User Thread
  • Quản lý bộ nhớ trong Java: bộ nhớ stack và bộ nhớ heap
  • Giới thiệu môn học Lập trình Web PHP

Mời bạn đánh giá bài viết

PHP programming

Điều hướng bài viết

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

is_numeric Finds whether a variable is a number or a numeric string

Description

is_numeric(mixed $value): bool

Parameters

value

The variable being evaluated.

Return Values

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

Changelog

VersionDescription
8.0.0 Numeric strings ending with whitespace ("42 ") will now return true. Previously, false was return 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($elementtrue) . " is numeric"PHP_EOL;
    } else {
        echo 
var_export($elementtrue) . " 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 ",
    
"\u{A0}9001"// non-breaking space
    
"9001\u{A0}"// non-breaking space
];

foreach (

$tests as $element) {
    if (
is_numeric($element)) {
        echo 
var_export($elementtrue) . " is numeric"PHP_EOL;
    } else {
        echo 
var_export($elementtrue) . " 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

sobolanx at gmail dot com

11 years ago

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

For example:

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

moskalyuk at gmail dot com

16 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

ben at chico dot com

8 years ago

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

kouber at saparev dot com

18 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);
}

Magnus Deininger, dma05 at web dot de

13 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:

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