Backend Development 4 min read

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

This article explains how PHP’s is_numeric() function checks whether a variable is numeric, demonstrates its usage with various examples—including simple variables and form input validation—and highlights special cases to watch out for when using the function.

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

In PHP programming, it is often necessary to determine whether a variable holds a numeric value; the language provides the convenient is_numeric() function for this purpose.

The is_numeric() function accepts a single argument—the variable to test—and returns a boolean value: true if the variable is numeric (including numeric strings) and false> otherwise.

Below is a basic code example illustrating how is_numeric() works with different types of variables:

$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 ; $var4 is a non‑numeric string, so the function returns false .

The function is also useful for validating form input. For instance, you can check whether a posted value is numeric before processing it:

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

Here, $_POST['number'] represents user‑submitted data; the script echoes a confirmation message if the input is numeric, otherwise it indicates the input is not numeric.

Be aware of special cases: certain strings that include a sign (+/-) or a trailing decimal point may not be treated as numeric. For example, is_numeric("12.34") returns true , whereas is_numeric("12.") returns false .

In summary, is_numeric() is a valuable PHP function for quickly determining whether a variable represents a valid numeric value, though developers should consider its handling of edge cases when using it in validation logic.

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