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.

php Courses
php Courses
php Courses
Using PHP’s is_numeric() Function to Check Numeric Values

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:

$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

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:

if (is_numeric($_POST['number'])) {<br/>    echo "输入的是一个数值";<br/>} else {<br/>    echo "输入的不是一个数值";<br/>}

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().

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPdata validationis_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

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.