PHP is_numeric() function


The is_numeric() function in PHP is used to determine whether a given variable is a number or a numeric string. It checks if the value can be interpreted as a number, either as an integer, float, or a numeric string.

Syntax:

is_numeric($value)

Parameters:

  • $value: The variable or value you want to check.

Return Value:

  • true if the value is numeric (can be interpreted as a number).
  • false if the value is not numeric.

Example 1: Checking Numeric Values

<?php // Numeric values var_dump(is_numeric(123)); // true (integer) var_dump(is_numeric(123.45)); // true (float) var_dump(is_numeric('123')); // true (numeric string) var_dump(is_numeric('123.45')); // true (numeric string) ?>

Output:

bool(true) bool(true) bool(true) bool(true)

Example 2: Non-numeric Values

<?php // Non-numeric values var_dump(is_numeric('Hello')); // false (non-numeric string) var_dump(is_numeric('123abc')); // false (alphanumeric string) var_dump(is_numeric(array())); // false (array) var_dump(is_numeric(null)); // false (null) ?>

Output:

bool(false) bool(false) bool(false) bool(false)

Example 3: Scientific Notation and Hexadecimal

<?php // Scientific notation var_dump(is_numeric('1.2e3')); // true (scientific notation, equivalent to 1.2 * 10^3) // Hexadecimal value (not numeric) var_dump(is_numeric('0x1A')); // false (hexadecimal string, not considered numeric) ?>

Output:

bool(true) bool(false)

Practical Usage:

  • is_numeric() is useful when you need to validate user input or check if a value can be used in mathematical operations.
  • It helps ensure that variables are valid numbers before performing calculations to avoid errors or unexpected behavior.

Summary:

  • is_numeric() checks whether a value is a valid number or numeric string.
  • It returns true for integers, floats, and numeric strings, and false for non-numeric values.