PHP is_numeric() Function

What is PHP is_numeric() Function?

If you want to check whether a value is of numeric type or not, use is_numeric() function. Instead of using value directly, you can use a variable to check its type too (Check example 1). A numeric string is a string that includes valid numbers.

All the following formats are valid numeric string-

FormatExample (Numeric string)
LNUM: [0-9]+“0”, “1”, “99” etc.
DNUM: ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)“.1”, “9.9”, “1.” etc.
EXPONENT_DNUM: (({LNUM} | {DNUM}) [eE][+-]? {LNUM})“1e+1”, “1e-9”, “1E5” etc.
INT_NUM_STRING: {WHITESPACES} [+-]? {LNUM} {WHITESPACES}“ +1”, “ -9 ” “ 5 ” etc.
FLOAT_NUM_STRING: {WHITESPACES} [+-]? ({DNUM} | {EXPONENT_DNUM}) {WHITESPACES}“ +.1”, “ -1E-1”, “ -5e-9 ” etc.

Check example 2.

Here, whitespace includes space, tab, and newline. Binary (e.g. 0b10100111001), hexadecimal (e.g. 0x41), and octal ((e.g. 0707)) are also valid numbers. Check example 3.

Syntax:

is_numeric(value)

Parameters:

The Function has 1 parameter which is required-

value (Required): It is the value or variable whose type to be evaluated. This parameter can accept any type of value/variable. Check example 1.

Return Values:

The function returns-

  • TRUE – if the value is of numeric type.
  • FALSE – if the value is not of type numeric.

How to use is_numeric() in coding?

As the function returns a Boolean value TRUE/FALSE, you can check this by conditional statements i.e. if statement, ternary operator. Choose one that suits your requirement. Depending on the result the conditional statement returns, your program flow progresses. Have a look at the code-

<?php
$Phone = $_POST[Phone'];
if(is_numeric($Phone)){
    echo "Phone is: " . $ Phone;
}else{
    echo "Phone must be a numeric number.";
}
?>

Examples:

Example 1: is_numeric() can check both type of a value or a variable-

<?php
var_dump(is_numeric(101)); echo "<br />";
var_dump(is_numeric("101")); echo "<br />";
$course = "101";
$lesson = 35;
var_dump(is_numeric($course)); echo "<br />";
var_dump(is_numeric($lesson)); echo "<br />";
var_dump(is_numeric("PHP for Beginners"));
?>

Output:

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

Explanation:

Line 2: The function can check type of a value (integer here) directly.

Line 3: The function can check type of a value (numeric string here) directly.

Line 6 – 7: The function can check type of a value by variable too.

Example 2: is_numeric() function examples-

<?php
var_dump(is_numeric(" 2\t")); echo "<br />";
var_dump(is_numeric(" 2 ")); echo "<br />";
var_dump(is_numeric(" -5e-9 ")); echo "<br />";
var_dump(is_numeric(".1")); echo "<br />";
var_dump(is_numeric("9.")); echo "<br />";
var_dump(is_numeric("1e-9")); echo "<br />";
$var = "35.15" + 100; var_dump(is_numeric($var)); echo "<br />";
var_dump(is_numeric("a35")); echo "<br />";
var_dump(is_numeric("-35")); echo "<br />";
var_dump(is_numeric("35-36")); echo "<br />";
var_dump(is_numeric(3.5)); echo "<br />";
var_dump(is_numeric("3.5 abc")); echo "<br />"; // It is a leading numeric string but not a numeric string.
var_dump(is_numeric(10e4)); echo "<br />";
?>

Output:

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

Explanation:

Line 2 – Line 13: They support valid numeric string format.

Line 14: Though it has leading numeric string, then it has letters, hence it is not a numeric string.

Example 3: More is_numeric() function examples-

<?php
echo "Is binary 0b10100111001 (decimal ". 0b10100111001.")  numeric? "; echo  is_numeric(0b10100111001)? "Yes":"No"; echo "<br />";
echo "Is octal 0707 (decimal ". 0707 .")  numeric? "; echo  is_numeric(0b10100111001)? "Yes":"No"; echo "<br />";
echo "Is hexadecimal 0x41 (decimal ". 0x41 .")  numeric? "; echo  is_numeric(0b10100111001)? "Yes":"No";
?>

Output:

Is binary 0b10100111001 (decimal 1337) numeric? Yes
Is octal 0707 (decimal 455) numeric? Yes
Is hexadecimal 0x41 (decimal 65) numeric? Yes

Why type checking is important?

Type checking is crucial part of any project. It can break your code if not done correctly.

  • Users may provide different type of data than they are asked to provide. For example, in the phone field, they may add string value. Though, you may apply client-side validation to prevent this error, you must implement server-side validation too with PHP.
  • As PHP can automatically change data type (Type Juggling) of a variable, you need to be careful situations like this when type conversion may occur. In the following code snippet, concatenating with sting “a” at line 3, the valid numeric string (+1 123 456 7890) becomes “+1 123 456 7890a” which is not a valid numeric number.
    <?php
    $Phone = "+1 123 456 7890";
    $Phone = $Phone . "a";
    var_dump($Phone);
    ?>
    

Practical Usages of is_numeric() Function:

  • Suppose you declared a table column named “RandomNo” which only accepts numeric data. Before inserting data in this column, you can check the data type with the is_numeric() function. Check the code snippet below-
    <?php
    $RandomNo = $_POST['RandomNo'];
    if(is_numeric($Status)){
        mysqli_query($connection, "INSERT INTO `product` (`RandomNo`, ...) 
                            VALUES ('$RandomNo',...)");
    }else{
        echo "Invalid RandomNo data type.";
    }
    ?>
    
  • Remember, form input is always string. That means whether you add an integer in a form field, it becomes string when you retrieve it. This is where is_nuremic() function plays a useful role to check data type. Suppose users are instructed to add only numeric data in the “RandomNo” field. But, one user added character or other type of data. Before further processing this data, you should at first check its type with is_numeric() function. Take a look at the code snippet below-
    <?php
    $RandomNo = $_POST['RandomNo'];
    if(is_numeric($RandomNo)){
        echo "RandomNo is: " . $RandomNo;
    }else{
        echo "Invalid RandomNo.";
    }
    ?>
    
  • Suppose you have a CSV file that contains two type of values – number and character. All are enclosed by quotes. To separate the numbers from the characters, use is_numeric() function. Look at the example below-
    <?php
    $rows = [
        'Alabama', '838', 'Alaska', '274', 'Arizona', '567', 'California', '2653'
    ];
    foreach ($rows as $row) {
        if (is_numeric($row)) {
            echo $row." ";
        } 
    }
    ?>
    

Notes on is_numeric() Function:

  • is_numeric() function doesn’t return true even though it is a valid number if the valid number contains thousand separators. The function below returns “ArgumentCountErro Fatal Error”.
    <?php
    var_dump(is_numeric(1,000,000));
    ?>
    
  • Empty string (“”) and string with space (“ ”) are not considered valid numeric strings. In both cases, the function returns FALSE. Check example below-
    <?php
    var_dump(is_numeric("")); echo "<br />";
    var_dump(is_numeric(" ")); echo "<br />";
    ?>
    
  • The followings are not considered as valid numeric string – NULL, Boolean value, array, class. In all cases, the function returns FALSE. Check example below-
    <?php
    var_dump(is_string(NULL)); echo "<br />";
    var_dump(is_string(FALSE)); echo "<br />";
    $arr = [1001]; var_dump(is_string($arr)); echo "<br />";
    class Language {var $total = 101;} $php = new Language(); var_dump(is_string($php));
    ?>
    

Caution:

Don’t use this function to check whether a value contains digits only as because this function returns TRUE if it contains for example period (.) or plus(+), or minus (-) in it. For example, a serial number shouldn’t use dot (.) in the digit, but, if you check this value with is_numeric() function, you’ll get an incorrect result. Use different functions in this case like preg_match() or preg_match_al() etc.

<?php
$serialNumber = "1110.2";
if(is_numeric($serialNumber)){
    echo "Valid numeric string"; // But it contains non-digit characters (dot)
}
if(!preg_match('/[^0-9]/', $serialNumber)){
    echo "Serial number contains only digits.";
}else{
    echo "Serial number contains non-digits characters";
}
?>

PHP Version Support:

PHP 4, PHP 5, PHP 7, PHP 8

Similar functions to is_numeric():

  • is_float()
  • is_string()
  • is_int() –
  • is_object() –
  • is_callable() –
  • is_null() –
  • is_resource() –
  • is_scalar() –
  • is_bool() –
  • is_iterable() –
  • is_long() –
  • is_integer() –
  • is_real() –
  • is_double() –
  • is_array() –

Summary: PHP is_numeric() Function

The correct data type can make or break your code. The function gives you the ability to check whether a variable is a numeric type variable. is_numeric() is one of the useful built-in variable-handling functions.

Reference:

https://www.php.net/manual/en/function.is-numeric.php

https://www.php.net/manual/en/language.types.numeric-strings.php