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 decimal points and trailing symbols.
In PHP programming, it is often necessary to determine whether a variable holds a numeric value; PHP provides the convenient is_numeric() function for this purpose.
The is_numeric() function checks a variable and returns a boolean true if the variable is numeric (including integers, floats, or numeric strings) and false otherwise.
Below is a basic code example that defines several variables and uses is_numeric() to test them:
$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 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. The following snippet checks a posted value named 'number' and echoes a message indicating whether the input is numeric:
if (is_numeric($_POST['number'])) {
echo "输入的是一个数值";
} else {
echo "输入的不是一个数值";
}Note that is_numeric() may not handle certain edge cases as expected; for instance, a trailing decimal point such as "12." is considered non‑numeric, while "12.34" returns true.
In summary, is_numeric() is a valuable PHP function for checking numeric values, but developers should be aware of its limitations with special formats.
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.