Master PHP’s is_numeric(): How to Validate Numbers Effectively
This article explains how PHP's is_numeric() function checks whether a variable is numeric, provides clear code examples for integers, floats, and numeric strings, demonstrates form input validation, and highlights special cases developers should watch out for.
In PHP programming, checking whether a variable holds a numeric value is a common task. PHP provides the convenient is_numeric() function, which returns a boolean true if the given variable is numeric and false otherwise.
The function accepts a single argument that can be an integer, a float, or a numeric string. It returns true for values such as 123, 3.14, or "42", and false for non‑numeric strings like "abc".
$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 above, $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, you can check $_POST['number'] with is_numeric() and output a message indicating whether the input is a valid number.
if (is_numeric($_POST['number'])) {
echo "输入的是一个数值";
} else {
echo "输入的不是一个数值";
}Be aware of special cases: a trailing decimal point such as is_numeric("12.") returns false, while is_numeric("12.34") returns true.
In summary, is_numeric() is a valuable PHP function for determining if a variable is numeric, enabling developers to handle numeric validation efficiently while keeping edge cases in mind.
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.
