How to Use is_numeric in PHP to Check Numbers

This article explains how to use the built-in is_numeric() function in PHP to determine whether a variable is a number or a numeric string. You will learn the basic syntax of the function, see practical code examples demonstrating various data types, and understand how it handles edge cases like scientific notation and whitespace.

Understanding is_numeric() in PHP

The is_numeric() function is a built-in PHP function used to evaluate whether a finding is a number or a numeric string. It returns true if the variable is an integer, a float, or a string that can be parsed as a number; otherwise, it returns false.

Syntax

is_numeric(mixed $value): bool

Code Examples

Here is how is_numeric() behaves with different types of data:

<?php
// Numeric values
is_numeric(42);         // true (Integer)
is_numeric(3.14);       // true (Float)

// Numeric strings
is_numeric("42");       // true (String integer)
is_numeric("3.14");     // true (String float)
is_numeric("-5");       // true (Negative number string)
is_numeric(" 1.5 ");    // true (String with leading/trailing whitespace)

// Scientific notation
is_numeric("1e3");      // true (1000)

// Non-numeric values
is_numeric("abc");      // false (Alphabetic string)
is_numeric("42abc");    // false (Alphanumeric string)
is_numeric(null);       // false (Null)
is_numeric(true);       // false (Boolean)
is_numeric([]);         // false (Array)
?>

Key Considerations

is_numeric() vs. is_int() and is_float()

Unlike is_int() or is_float(), which strictly check the data type of the variable, is_numeric() is more permissive. For example, is_int("42") will return false because the input is a string, whereas is_numeric("42") will return true because the content of the string represents a valid number.

Use is_numeric() when validation is required for form inputs or API requests, as web data is often transmitted as strings.

Whitespace and Signs

The function successfully validates numeric strings that contain leading or trailing spaces (e.g., " 100 ") as well as strings containing positive or negative signs (e.g., "-50" or "+12").

Hexadecimal Strings

Note that since PHP 7.0, hexadecimal strings (such as "0xf4c") are no longer considered numeric by is_numeric() and will return false.