Understanding PHP’s is_numeric() Function: Usage, Examples, and Edge Cases
This article explains PHP’s is_numeric() function, shows how it determines whether a variable is numeric, provides multiple code examples—including simple variable checks and form input validation—and discusses special cases such as trailing decimal points.
In PHP programming, you often need to determine whether a variable is numeric. PHP provides the convenient is_numeric() function, which checks a variable and returns a boolean true or false.
The function accepts a single argument that can be an integer, float, or a numeric string. If the argument is numeric, the function returns true; otherwise, it returns false.
Below is a basic usage example:
$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 stringIn this example, $var1, $var2, and $var3 are considered numeric, so is_numeric() returns true, while $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, if the user submits a numeric value, the script outputs a confirmation message; otherwise, it indicates the input is not numeric.
Be aware of special cases: a leading sign (+/-) or a trailing decimal point can affect the result. For example, is_numeric("12.34") returns true, but is_numeric("12.") returns false.
In summary, is_numeric() is a valuable PHP function for checking whether a variable represents a valid number, but developers should consider its handling of edge cases when using it in validation logic.
Hopefully this guide helps beginner PHP developers better understand and use the is_numeric() function.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.