Backend Development 4 min read

How to Use PHP's is_numeric() Function to Determine if a Variable Is Numeric

This article explains PHP's is_numeric() function, shows how it checks whether variables—including integers, floats, and numeric strings—are numeric, provides code examples for direct checks and form validation, and discusses special cases to watch out for.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP's is_numeric() Function to Determine if a Variable Is Numeric

In PHP programming, you often need to determine whether a variable holds a numeric value; the built‑in is_numeric() function checks this and returns a boolean true or false.

The function accepts a single argument, which can be an integer, a floating‑point number, or a numeric string; it returns true for numeric inputs and false otherwise.

Example 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 empty string

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

The function is also useful for validating form input. For instance, you can check a posted value with:

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

Here, $_POST['number'] is examined; if it is numeric, a success message is printed, otherwise an error message is shown.

Be aware of special cases: a leading plus/minus sign or a trailing decimal point is not considered part of a numeric value. For example, is_numeric("12.34") returns true, but is_numeric("12.") returns false.

In summary, is_numeric() is a handy PHP function for verifying that a variable contains a valid numeric value, though developers should handle edge cases such as signs and incomplete decimal numbers appropriately.

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