Master PHP’s is_numeric(): How to Validate Numbers Efficiently
This article explains how PHP's is_numeric() function determines whether a variable is numeric, demonstrates practical code examples for variables and form inputs, and highlights special cases developers should watch out for when validating numeric data.
In PHP programming, you often need to determine whether a variable is numeric. PHP provides the convenient function is_numeric() for this purpose.
The is_numeric() function checks if a variable is a number and returns a boolean value—true if it is numeric, false otherwise. It accepts integers, floating‑point numbers, or numeric strings as its single argument.
Below is a code example that illustrates how is_numeric() works with different variable types:
$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 an empty stringIn this example, $var1, $var2, and $var3 are considered numeric, so is_numeric() returns true. The variable $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 submitted value is numeric before processing it:
if (is_numeric($_POST['number'])) {
echo "Input is a numeric value";
} else {
echo "Input is not a numeric value";
}Here, $_POST['number'] represents a user‑provided value. If it is numeric, the script outputs a confirmation message; otherwise, it indicates the input is not numeric.
Be aware of special cases: certain formats are not treated as numeric. For example, is_numeric("12.34") returns true, but is_numeric("12.") returns false because the trailing decimal point is considered invalid.
In summary, is_numeric() is a valuable PHP function for checking whether a variable holds a valid numeric value, simplifying data validation tasks, though developers should handle edge cases such as incomplete decimal representations.
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.
