Using PHP’s is_numeric() Function to Determine Numeric Values
This article explains PHP’s is_numeric() function, detailing its purpose, usage, return values, and edge cases, and provides multiple code examples—including variable checks and form input validation—to help developers reliably determine whether a variable or user input is numeric.
In PHP programming, determining whether a variable is numeric is common; the built‑in is_numeric() function checks this and returns a boolean true or false.
The function accepts a single argument that can be an integer, float, or numeric string; it returns true for numeric values 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 stringIn 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:
if(is_numeric($_POST['number'])) {
echo "输入的是一个数值";
} else {
echo "输入的不是一个数值";
}Here, the posted 'number' field is checked; the script echoes a message indicating whether the input is numeric.
Note that certain edge cases are not handled ideally: a standalone plus or minus sign or a trailing decimal point are considered non‑numeric. For example, is_numeric("12.34") returns true, but is_numeric("12.") returns false.
In summary, is_numeric() is a valuable PHP function for verifying numeric variables and user input, but developers should be aware of its limitations with special cases.
This guide aims to help beginner PHP developers understand and correctly use is_numeric() .
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.