Mastering PHP’s is_numeric(): Accurately Detect Numeric Values
This guide explains how PHP’s is_numeric() function checks whether a variable is numeric, demonstrates usage with various data types and form inputs, highlights edge cases like trailing decimal points, and provides clear code examples for reliable validation.
In PHP development you often need to determine whether a variable holds a numeric value; the built‑in is_numeric() function provides a simple way to do this.
The function accepts a single argument – the variable to test – which can be an integer, a floating‑point number, or a numeric string. It returns true if the value is considered numeric and false otherwise.
$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 numeric, so is_numeric() returns true. $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 a posted value before processing it:
if (is_numeric($_POST['number'])) {
echo "输入的是一个数值";
} else {
echo "输入的不是一个数值";
}Here $_POST['number'] is examined; if it is numeric the script outputs a confirmation, otherwise it reports that the input is not numeric.
Be aware of special cases: signs (+/‑) and a trailing decimal point are treated as non‑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 verifying that a variable represents a valid number, enabling reliable data handling while requiring attention to edge‑case inputs.
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.
