Using PHP’s is_numeric() Function to Check Numeric Values
This article explains PHP’s is_numeric() function, detailing how it determines whether a variable is numeric, provides multiple code examples—including simple variable checks and form input validation—and discusses special cases such as trailing decimal points, helping beginners reliably validate numeric data in PHP.
In PHP programming, the is_numeric() function is provided to check whether a variable is numeric 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.
Below is a code example demonstrating the use of is_numeric() with several variables:
<code>$var1 = 123;<br/>$var2 = 3.14;<br/>$var3 = "42";<br/>$var4 = "abc";<br/><br/>echo is_numeric($var1); // outputs 1<br/>echo is_numeric($var2); // outputs 1<br/>echo is_numeric($var3); // outputs 1<br/>echo is_numeric($var4); // outputs empty string</code>In 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 can also be used to validate form input; for instance, checking a posted value before processing:
<code>if (is_numeric($_POST['number'])) {<br/> echo "输入的是一个数值";<br/>} else {<br/> echo "输入的不是一个数值";<br/>}</code>Here, the posted 'number' field is tested with is_numeric() , outputting a message indicating whether the input is numeric.
Note that is_numeric() has edge cases: strings containing only a plus/minus sign or a trailing decimal point are not considered numeric (e.g., is_numeric("12.") returns false).
In summary, is_numeric() is a useful PHP function for determining if a variable holds a valid numeric value, though developers should be aware of its handling of special cases.
The article 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.