Home > Backend Development > PHP Problem > PHP determines whether a string is a number

PHP determines whether a string is a number

(*-*)浩
Release: 2023-02-24 15:08:01
Original
21786 people have browsed it

PHP determines whether a string is a number

is_numeric — Detect whether a variable is a number or a numeric character (Recommended learning: PHP Programming from Beginner to Master)

<?php
$tests = array(
    "31", 
    1380, 
    "1e4", 
    "not numeric", 
    array(), 
    9.1
);

foreach ($tests as $element) {
    if (is_numeric($element)) {
        echo "&#39;{$element}&#39; is numeric", PHP_EOL;
    } else {
        echo "&#39;{$element}&#39; is NOT numeric", PHP_EOL;
    }
}
?>
Copy after login

Program execution result:

&#39;31&#39; is numeric
&#39;1380&#39; is numeric
&#39;1e4&#39; is numeric
&#39;not numeric&#39; is NOT numeric
&#39;Array&#39; is NOT numeric
&#39;9.1&#39; is numeric
Copy after login

The string 1e4 is also judged as a number.

The is_numeric function not only supports decimal numbers, but also supports hexadecimal type numbers. Therefore, when verifying pure natural numbers such as QQ numbers in use, you must cooperate with the intval() integer function.

<?php
    $id = 0xff33669f;
    if (is_numeric($id)) 
    echo $id, &#39;符合要求。&#39;;//output 4281558687符合要求。
    else 
    echo $id, &#39;不符合要求。&#39;;
?>
Copy after login

If you need to determine an integer, you can use the is_int() function to avoid the situation where some strings are also regarded as legal numbers.

is_numeric can determine whether a variable is a number or a numeric string, but its determination range is too wide. Integers, decimals, exponential representations and hexadecimal values ​​will all pass the judgment. When usually determining the ID, it is a bit inappropriate to use it.

Today I discovered a new judgment function: ctype_digit, which can only judge integers, which is better than is_numeric. Other functions include ctype_xdigit to determine hexadecimal integers, ctype_alpha to determine letters, and so on.

The above is the detailed content of PHP determines whether a string is a number. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template