Master PHP’s is_numeric(): How to Validate Numbers Efficiently
This guide explains PHP’s is_numeric() function, how it determines whether a variable is numeric, demonstrates practical code examples—including simple variable checks and form input validation—and highlights special cases developers should watch out for.
In PHP programming, you often need to determine whether a variable is numeric. PHP provides a convenient function is_numeric() that checks a variable and returns a boolean true or false. This article introduces the function and provides code examples. is_numeric() can detect a numeric variable. It accepts one argument, which may be an integer, a float, or a numeric string. It returns true for numeric values and false otherwise.
Example code:
$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 the example, $var1, $var2, and $var3 are numeric, so is_numeric() returns true; $var4 is a non‑numeric string, so it returns false. is_numeric() can also be used to validate form input. Example:
if (is_numeric($_POST['number'])) {
echo "Input is a number";
} else {
echo "Input is not a number";
}Note that certain edge cases are not handled ideally. For instance, a trailing decimal point is considered non‑numeric: is_numeric("12.") returns false, while is_numeric("12.34") returns true.
In summary, is_numeric() is a useful PHP function for checking whether a variable is numeric, enabling easy validation of numeric data, but be aware of special cases.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
