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

This article explains PHP’s is_numeric() function, demonstrates how it determines whether variables or form inputs are numeric through detailed examples, and highlights special cases developers should watch for when validating numeric data.

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

In PHP programming, determining whether a variable holds a numeric value is a common task; the built‑in is_numeric() function provides a convenient way to perform this check and returns a boolean result.

The function accepts a single argument, which can be an integer, a floating‑point number, or a numeric string, and returns true if the value is considered numeric 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 an empty string

In this example, $var1, $var2, and $var3 are 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:

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

Here, the value submitted via $_POST['number'] is checked; the script echoes a message indicating whether the input is numeric.

Developers should be aware of special cases: a leading sign (+/-) or a trailing decimal point is not considered part of a numeric value. For example, is_numeric("12.34") returns true, while is_numeric("12.") returns false.

In summary, is_numeric() is a valuable PHP function for verifying numeric data, but attention to edge cases is necessary to ensure correct validation.

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

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backenddata validationis_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

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.