Backend Development 4 min read

Using PHP’s is_numeric() Function to Check Numeric Values

This article explains how PHP’s is_numeric() function determines whether a variable is numeric, demonstrates its usage with various data types, shows practical form‑validation examples, and highlights special cases developers should be aware of.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP’s is_numeric() Function to Check Numeric Values

In PHP programming, it is often necessary to determine whether a variable holds a numeric value. PHP provides the convenient is_numeric() function for this purpose, which returns a boolean true if the variable is numeric and false otherwise.

The function accepts integers, floating‑point numbers, or numeric strings as its argument. If the supplied value qualifies as a number, is_numeric() returns true; otherwise it returns false.

Below is a code example illustrating typical usage:

$var1 = 123;
$var2 = 3.14;
$var3 = "42";
$var4 = "abc";

echo is_numeric($var1);  // outputs 1
echo is_numeric($var2);  // outputs 1
echo is_numeric($var3);  // outputs 1
echo is_numeric($var4);  // outputs an empty string

In this example, $var1 , $var2 , and $var3 are considered numeric, so is_numeric() returns true for them, while $var4 is a non‑numeric string, resulting in false.

The function is also useful for validating form input. For instance, when a user submits a form, you can verify that the submitted value is numeric before processing it:

if (is_numeric($_POST['number'])) {
    echo "输入的是一个数值";
} else {
    echo "输入的不是一个数值";
}

Here, $_POST['number'] represents the user‑provided input. If it is numeric, the script outputs a message confirming the numeric input; otherwise, it indicates that the input is not numeric.

Note that is_numeric() has some edge‑case behavior. For example, a string containing a decimal point without following digits (e.g., "12.") is considered non‑numeric, while a properly formatted decimal string (e.g., "12.34") returns true.

In summary, is_numeric() is a valuable PHP function for checking whether a variable is a valid number, simplifying validation logic for developers, but special cases such as trailing decimal points should be handled with care.

This guide aims to help beginner PHP developers understand and effectively use the is_numeric() function.

backendphp-functionsis_numericnumeric validation
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.