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

This article explains PHP’s is_numeric() function, detailing how it determines whether a variable is numeric, providing example code for direct checks, form input validation, and discussing edge cases such as trailing decimal points, making it a useful guide for beginner backend developers.

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

PHP provides the is_numeric() function to determine whether a given variable is a number, returning true for numeric values and false otherwise. The function accepts integers, floats, or numeric strings as its single argument.

The following example demonstrates basic usage of is_numeric() with different variable types:

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

echo is_numeric($var1);  // 输出1
echo is_numeric($var2);  // 输出1
echo is_numeric($var3);  // 输出1
echo is_numeric($var4);  // 输出空字符串

In this snippet, $var1, $var2, and $var3 are considered numeric, so is_numeric() returns true (displayed as 1), while $var4 is a non‑numeric string, resulting in false (an empty string output).

The function is also useful for validating form input. The code below checks whether a posted value named number is numeric and echoes an appropriate message:

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

Here, $_POST['number'] represents the user‑submitted value. If it passes the is_numeric() test, the script outputs “输入的是一个数值”; otherwise it outputs “输入的不是一个数值”.

Note that is_numeric() has some edge‑case behavior: a string containing only a sign (+/-) or a trailing decimal point is not considered numeric. For example, is_numeric("12.34") returns true, but is_numeric("12.") returns false.

In summary, is_numeric() is a handy PHP function for checking whether a variable holds a valid numeric value, useful for both simple variable checks and form validation, though developers should be aware of its handling of special cases.

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.

BackendPHPphp-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

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.