Backend Development 4 min read

Using PHP’s is_numeric() Function to Determine If a Variable Is Numeric

This article explains how the PHP is_numeric() function checks whether a variable is numeric, returns a boolean result, and demonstrates its usage with code examples for direct variable checks and form input validation, while also highlighting special edge cases to watch out for.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP’s is_numeric() Function to Determine If a Variable Is Numeric

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 accepts a single argument—the variable to be examined—and returns true if the variable is numeric (including integers, floats, or numeric strings) and false otherwise.

Below is a code example that demonstrates the function:

<code>$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 string</code>

In this example, $var1 , $var2 , and $var3 are considered numeric, so is_numeric() returns true ; $var4 is a non‑numeric string, so the function returns false .

The function can also be used to validate form input. For instance, when a user submits a form, you can verify that the submitted value is numeric before processing it:

<code>if (is_numeric($_POST['number'])) {
    echo "The input is a numeric value";
} else {
    echo "The input is not a numeric value";
}</code>

Here, $_POST['number'] represents the user‑provided value; is_numeric() determines whether it is numeric and outputs the appropriate message.

Be aware of some special cases: a leading plus/minus sign or a trailing decimal point may cause unexpected results. For example, is_numeric("12.34") returns true , whereas is_numeric("12.") returns false .

In summary, is_numeric() is a useful PHP function for checking if a variable is numeric, enabling straightforward validation of numeric data, but developers should consider its handling of edge cases.

PHPCode Exampleis_numericnumeric validation
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.