is_numeric

(PHP 4, PHP 5, PHP 7, PHP 8)

is_numeric Détermine si une variable est un nombre ou une chaîne numérique

Description

is_numeric(mixed $value): bool

Détermine si la variable donnée est un nombre ou une chaîne numérique.

Liste de paramètres

value

La variable à évaluer.

Valeurs de retour

Retourne true si value est un nombre ou une chaîne numérique, false sinon.

Historique

Version Description
8.0.0 Les chaînes numériques terminant avec des caractères d'espacement blanc ("42 ") retourneront désormais true. Auparavant, false était retourné à la place.

Exemples

Exemple #1 Exemple avec is_numeric()

<?php
$tests
= array(
"42",
1337,
0x539,
02471,
0b10100111001,
1337e0,
"0x539",
"02471",
"0b10100111001",
"1337e0",
"not numeric",
array(),
9.1,
null,
'',
);

foreach (
$tests as $element) {
if (
is_numeric($element)) {
echo
var_export($element, true) . " est numérique", PHP_EOL;
} else {
echo
var_export($element, true) . " N'est PAS numérique", PHP_EOL;
}
}
?>

L'exemple ci-dessus va afficher :

'42' est numérique
1337 est numérique
1337 est numérique
1337 est numérique
1337 est numérique
1337.0 est numérique
'0x539' N'est PAS numérique
'02471' est numérique
'0b10100111001' N'est PAS numérique
'1337e0' est numérique
'not numeric' N'est PAS numérique
array (
) N'est PAS numérique
9.1 est numérique
NULL N'est PAS numérique
'' N'est PAS numérique

Exemple #2 is_numeric() avec des caractères d'espacement blanc

<?php
$tests
= [
" 42",
"42 ",
"\u{A0}9001", // non-breaking space
"9001\u{A0}", // non-breaking space
];

foreach (
$tests as $element) {
if (
is_numeric($element)) {
echo
var_export($element, true) . " is numeric", PHP_EOL;
} else {
echo
var_export($element, true) . " is NOT numeric", PHP_EOL;
}
}
?>

Résultat de l'exemple ci-dessus en PHP 8 :

' 42' is numeric
'42 ' is numeric
' 9001' is NOT numeric
'9001 ' is NOT numeric

Résultat de l'exemple ci-dessus en PHP 7 :

' 42' is numeric
'42 ' is NOT numeric
' 9001' is NOT numeric
'9001 ' is NOT numeric

Voir aussi

add a note add a note

User Contributed Notes 40 notes

up
105
dave dot marr at gmail dot com
12 years ago
If you want the numerical value of a string, this will return a float or int value:

<?php
function get_numeric($val) {
  if (
is_numeric($val)) {
    return
$val + 0;
  }
  return
0;
}
?>

Example:
<?php
get_numeric
('3'); // int(3)
get_numeric('1.2'); // float(1.2)
get_numeric('3.0'); // float(3)
?>
up
75
sobolanx at gmail dot com
13 years ago
Note that the function accepts extremely big numbers and correctly evaluates them.

For example:

<?php
    $v
= is_numeric ('58635272821786587286382824657568871098287278276543219876543') ? true : false;
   
   
var_dump ($v);
?>

The above script will output:

bool(true)

So this function is not intimidated by super-big numbers. I hope this helps someone.

PS: Also note that if you write is_numeric (45thg), this will generate a parse error (since the parameter is not enclosed between apostrophes or double quotes). Keep this in mind when you use this function.
up
54
Martyn Ranyard
13 years ago
The documentation does not clarify what happens if you the input is an empty string - it correctly returns false in my experience.  Useful to state these odd cases, for when you see code that checks for an empty string and is_numeric, you can tell it's a waste of a comparison.
up
19
tanguy_barsik at hotmail dot com
7 years ago
for strings, it return true only if float number has a dot

is_numeric( '42.1' )//true
is_numeric( '42,1' )//false
up
8
charlike dot mike at mail dot bg
10 years ago
I think that is best check solution if u want to create real calculator for example :)

<?php
function is_number($var)
{
    if (
$var == (string) (float) $var) {
        return (bool)
is_numeric($var);
    }
    if (
$var >= 0 && is_string($var) && !is_float($var)) {
        return (bool)
ctype_digit($var);
    }
    return (bool)
is_numeric($var);
}

is_number(12); // true
is_number(-12); // true
is_number(-12.2); // true
is_number("12"); // true
is_number("-124.3"); // true
is_number(0.8); // true
is_number("0.8"); // true
is_number(0); // true
is_number("0"); // true
is_number(NULL); // false
is_number(true); // false
is_number(false); // false
is_number("324jdas32"); // false
is_number("123-"); // false
is_number(1e7); // true
is_number("1e7"); // true
is_number(0x155); // true
is_number("0x155"); // false
?>
up
18
Stephen
17 years ago
The documentation is not completely precise here. is_numeric will also return true if the number begins with a decimal point  and/or a space, provided a number follows (rather than a letter or punctuation). So, it doesn't necessarily have to start with a digit.
up
1
vikramverma214 at gmail dot com
8 years ago
check if given string is mobile number

function filterNumber($str)
        {
            //remove non number
            $count = strlen($str);
            $newNumber = "";
            for($i = 0; $i<$count; $i++)
            {
                if(is_numeric($str[$i]))
                    $newNumber .= $str[$i];
            }

            //removes leading 0s
            $newNumber = ltrim($newNumber, '0');

            //remove 91 in starting, 91 is specific to Indian Numbers
            if(strlen($newNumber) == 12)
            {
                if(substr($newNumber, 0, 2) == '91')
                    $newNumber = substr($newNumber, 2);
            }

            //final check for length 10
            if(strlen($newNumber) != 10 )
                return null;
            else
                return $newNumber;
        }
up
9
moskalyuk at gmail dot com
17 years ago
is_numeric fails on the hex values greater than LONG_MAX, so having a large hex value parsed through is_numeric would result in FALSE being returned even though the value is a valid hex number
up
11
sebu
18 years ago
Referring to previous post "Be aware if you use is_numeric() or is_float() after using set_locale(LC_ALL,'lang') or set_locale(LC_NUMERIC,'lang')":

This is totally wrong!

This was the example code:

-----
  set_locale(LC_NUMERIC,'fr');
  is_numeric(12.25); // Return False
  is_numeric(12,25); // Return True
  is_float(12.25); //Return False
  is_float(12,25); //Return True
-----

This is nonsense!

- set_locale() does not exist, you must use setlocale() instead
- you have to enclose 12,25 with quotes; otherwise PHP will think that
the function gets _two_ arguments: 12 and 25 (depending on PHP version and setup you may additionally get a PHP warning)
- if you don't enclose 12,25 with quotes the first argument will be the inspected value (12), the second value (25) is discarded. And is_numeric(12) and is_float(12) is always TRUE

Corrected Example:

----
  setlocale(LC_NUMERIC,'fr');
  is_numeric(12.25); // Return True
  is_numeric("12,25"); // Return False
  is_float(12.25); //Return True
  is_float("12,25"); //Return False
----

Remarks:
- is_float(12.25) is _always_ TRUE, 12.25 is a PHP language construct (a "value") and the way PHP interpretes files is definitely _not_ affected by the locale
- is_float("12,25") is _always_ FALSE, since is_float (other than is_numeric): if the argument is a string then is_float() always returns FALSE since it does a strict check for floats

And the corrected example shows: you get the _same_ results for every possible locale, is_numeric() does not depend on the locale.
up
7
andi_nrw at hotmail dot com
21 years ago
<?php
/* This function is not useful if you want
to check that someone has filled in only
numbers into a form because for example
4e4 and 444 are both "numeric".

I used a regular expression for this problem
and it works pretty good. Maybe it is a good
idea to write a function and then to use it.

$input_number = "444"; // Answer 1
$input_number = "44 "; // Answer 2
$input_number = "4 4"; // Answer 2
$input_number = "4e4"; // Answer 2
$input_number = "e44"; // Answer 2
$input_number = "e4e"; // Answer 2
$input_number = "abc"; // Answer 2
*/
$input_number = "444";

if (
preg_match ("/^([0-9]+)$/", $input_number)) {
     print
"Answer 1";
} else {
     print
"Answer 2";
}
?>
up
6
eagleflyer2 at lycos dot com
21 years ago
Hi !
Many of you may have experienced that the 'is_numeric' function seems to fail always when form entries are checked against their variable type. So the function seems to return  'false' even if the form entry was aparently a number or numeric string.

The solution is pretty simple and no subroutines or fancy operations are necessary to make the 'is_numeric' function usable for form entry checks:

Simply strip off all (invisible) characters that may be sent along with the value when submitting a form entry.

Just use the 'trim' function before 'is_numeric'.

Example:

$variable = trim($variable);
if (is_numeric($variable)
{...#do something#...}
else
{...#do something else#...}
up
8
andrea dot vacondio at gmail dot com
18 years ago
Two simple functions using is_numeric:

<?php

function is_odd($num){
     return (
is_numeric($num)&($num&1));
}

function
is_even($num){
     return (
is_numeric($num)&(!($num&1)));
}

//examples
echo "1: odd? ".(is_odd(1)? "TRUE": "FALSE")."<br />";
//is_numeric(0) returns true
echo "0: odd? ".(is_odd(0)? "TRUE": "FALSE")."<br />";
echo
"6: odd? ".(is_odd(6)? "TRUE": "FALSE")."<br />";
echo
"\"italy\": odd? ".(is_odd("italy")? "TRUE": "FALSE")."<br />";
echo
"null: odd? ".(is_odd(null)? "TRUE": "FALSE")."<br /><br />";
echo
"1: even? ".(is_even(1)? "TRUE": "FALSE")."<br />"
echo
"0: even? ".(is_even(0)? "TRUE": "FALSE")."<br />";
echo
"6: even? ".(is_even(6)? "TRUE": "FALSE")."<br />";
echo
"\"italy\": even? ".(is_even("italy")? "TRUE": "FALSE")."<br />"
echo
"null: even? ".(is_even(null)? "TRUE": "FALSE")."<br />";

?>
And here is the result:
1: odd? TRUE
0: odd? FALSE
6: odd? FALSE
"italy": odd? FALSE
null: odd? FALSE

1: even? FALSE
0: even? TRUE
6: even? TRUE
"italy": even? FALSE
null: even? FALSE
up
7
jamespam at hotmail dot com
18 years ago
Here's a function to determine if a variable represents a whole number:

function is_whole_number($var){
  return (is_numeric($var)&&(intval($var)==floatval($var)));
}

just simple stuff...
is_whole_number(2.00000000001); will return false
is_whole_number(2.00000000000); will return true
up
5
Vasiliy Makogon
7 years ago
If you want detect integer of float values, which presents as pure int or float, and presents as string values, use this functions:

<?php
function isInteger($val)
{
    if (!
is_scalar($val) || is_bool($val)) {
        return
false;
    }
    if (
is_float($val + 0) && ($val + 0) > PHP_INT_MAX) {
        return
false;
    }
    return
is_float($val) ? false : preg_match('~^((?:\+|-)?[0-9]+)$~', $val);
}

function
isFloat($val)
{
    if (!
is_scalar($val)) {
        return
false;
    }
    return
is_float($val + 0);
}

foreach ([
   
'11111111111111111', 11111111111111111, // > PHP_INT_MAX - presents in PHP as float
   
1, '10', '+1', '1.1', 1.1, .2, 2., '.2', '2.',
   
'-2.', '-.2', null, [], true, false, 'string'
] as $value) {
    echo
$value . ':' . gettype($value) . ' is Integer? - '  . (isInteger($value) ? 'yes' : 'no') . PHP_EOL;
    echo
$value . ':' . gettype($value) . ' is Float? - '  . (isFloat($value) ? 'yes' : 'no') . PHP_EOL;
}
?>

Output:

11111111111111111:string is Integer? - no
11111111111111111:string is Float? - yes
1,1111111111111E+16:double is Integer? - no
1,1111111111111E+16:double is Float? - yes
1:integer is Integer? - yes
1:integer is Float? - no
10:string is Integer? - yes
10:string is Float? - no
+1:string is Integer? - yes
+1:string is Float? - no
1.1:string is Integer? - no
1.1:string is Float? - yes
1,1:double is Integer? - no
1,1:double is Float? - yes
0,2:double is Integer? - no
0,2:double is Float? - yes
2:double is Integer? - no
2:double is Float? - yes
.2:string is Integer? - no
.2:string is Float? - yes
2.:string is Integer? - no
2.:string is Float? - yes
-2.:string is Integer? - no
-2.:string is Float? - yes
-.2:string is Integer? - no
-.2:string is Float? - yes
:NULL is Integer? - no
:NULL is Float? - no
Array:array is Integer? - no
Array:array is Float? - no
1:boolean is Integer? - no
1:boolean is Float? - no
:boolean is Integer? - no
:boolean is Float? - no
string:string is Integer? - no
string:string is Float? - no
up
7
mdallaire at virtuelcom dot com
19 years ago
Sometimes, we need to have no letters in the number and is_numeric does not quit the job.
You can try it this ways to make sure of the number format:

    function new_is_unsigned_float($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^([0-9])+([\.|,]([0-9])*)?$",$val);
    }

    function new_is_unsigned_integer($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^([0-9])+$",$val);
    }

    function new_is_signed_float($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^-?([0-9])+([\.|,]([0-9])*)?$",$val);
    }

    function new_is_signed_integer($val) {
        $val=str_replace(" ","",trim($val));
        return eregi("^-?([0-9])+$",$val);
    }

It returns 1 if okay and returns nothing "" if it's bad number formating.
up
6
namik at hub-cafe dot net
18 years ago
I needed a number_suffix function that takes numbers with thousand seperators (using number_format() function).  Note that this doesn't properly handle decimals.

Example:
<?= number_suffix('1,021') ?> returns: 1,021st

Also, increasing the range above the condition statements increases efficiency.  That's almost 20% of the numbers between 0 and 100 that get to end early.

<?
  function number_suffix($number)
  {
    // Validate and translate our input
    if ( is_numeric($number) )
    {
      // Get the last two digits (only once)
      $n = $number % 100;
    } else {
     // If the last two characters are numbers
     if ( preg_match( '/[0-9]?[0-9]$/', $number, $matches ) )
     {
       // Return the last one or two digits
       $n = array_pop($matches);
     } else {
       // Return the string, we can add a suffix to it
       return $number;
     }
    }
    // Skip the switch for as many numbers as possible.
    if ( $n > 3 && $n < 21 )
      return $number . 'th';

    // Determine the suffix for numbers ending in 1, 2 or 3, otherwise add a 'th'
    switch ( $n % 10 )
    {
      case '1': return $number . 'st';
      case '2': return $number . 'nd';
      case '3': return $number . 'rd';
      default:  return $number . 'th';
    }
  }
?>
up
4
Elwin van Huissteden
16 years ago
To James holwell:

Maybe your function was more strickt, but profides FALSE to any numeric string that wasnt written in the English/American notition. To enable a person to use the both the English/American and the rest of the world's way:

<?php
 
function my_is_numeric($value)
  {
   return (
preg_match ("/\A(-){0, 1}([0-9]+)((,|.)[0-9]{3, 3})*((,|.)[0-9]){0, 1}([0-9]*)\z/" ,$value) == 1);
  }
?>

Other than that, i'd recommend using yours, if it works (i havent tested either yours or mine)
By using mine, there might be a slight chance to not being able to do calculations with the numeric string if it's not the English/American way.

(*Note:
-the E/A way of writing 1 million (with decimal for 1/50): 1,000,000.02
-the global way of writing 1 million (with decimal for 1/50): 1.000.000,02
up
6
rontarrant at NO_SPAMsympatico dot ca
17 years ago
Here's an even simpler pair of functions for finding out if a number is odd or even:

function IS_ODD($number) { return($number & 1); }

function IS_EVEN($number) { return(!($number & 1)); }

Test:
$myNumber = 151;

if(IS_ODD($myNumber))
    echo("number is odd\n");
else
    echo("number is NOT odd\n");

if(IS_even($myNumber))
    echo("number is even\n");
else
    echo("number is NOT even\n");

Results:
number is odd
number is NOT even
up
4
joe at kewlmail dot net
20 years ago
Here is a simple function that I found usefull for filtering user input into numbers. Basically, it attempts to fix fat fingering. For example:

$userString = "$654.4r5";

function numpass_filter($userString){ 
    $money = explode(".", $userString);
    //now $money[0] = "$645" and $money[1] = "4r5"

    //next remove all characters save 0 though 9
    //in both elements of the array
    $dollars = eregi_replace("[^0-9]", null, $money[0]);
    $cents = eregi_replace("[^0-9]", null, $money[1]);

    //if there was a decimal in the original string, put it back
    if((string)$cents!=null){
        $cents = "." . $cents;
    }

   $result = $dollars . $cents;

    return($result);
}

The output in this case would be '654.45'.
Please note that this function will work properly unless the user fat fingers an extra decimal in the wrong place.
up
4
stew_wilde at hotmail dot com
20 years ago
When using the exec() function in php to execute anther php script, any command line arguments passed the script will lose their type association, regardless of whether they are numeric or not, the same seems to hold true for strings as well.

ie : two scripts test.php:

<?php
$val
= trim($argv[1]);
echo
is_string($val);
?>

and testwrapper.php:

<?php
$tmp
= 5;
exec("php ./test.php ".$tmp);
?>

Executing testwrapper.php on the command line will echo nothing (ie false), and false will be returned regardless of any escaping of parameters or other such attempts to overcome this.  The solution then is to explicitly cast $val in test.php to be an int and then is_numeric will work.  But as stated the same test was performed using a string for $val and the is_string() function and the same thing occurs.  Not the end of the world, but something to be aware of :)
up
4
Kiam
14 years ago
empty(trim($test, '+-.,0123456789')) doesn't assure you $test contains a number. It returns TRUE also for a string containing ".+1234.56", which is not a valid number.
up
4
kouber at saparev dot com
20 years ago
Note that this function is not appropriate to check if "is_numeric" for very long strings. In fact, everything passed to this function is converted to long and then to a double. Anything greater than approximately 1.8e308 is too large for a double, so it becomes infinity, i.e. FALSE. What that means is that, for each string with more than 308 characters, is_numeric() will return FALSE, even if all chars are digits.

However, this behaviour is platform-specific.

http://www.php.net/manual/en/language.types.float.php

In such a case, it is suitable to use regular expressions:

function is_numeric_big($s=0) {
  return preg_match('/^-?\d+$/', $s);
}
up
5
Nitrogen
13 years ago
I find it a little weird that people are having issues with ordinal numbers, it's pretty easy..
Notes are in the commenting, check out the example outputs.

<?php

function ordinal($i='') {
 
// a temporary value we can change, and keep the original value.
 
$o=$i;

 
// suffixes = 0th, 1st, 2nd, third == zeroth, first, second, third
 
$s=array('th','st','nd','rd');

 
// if input just so happens to be a string, we check to make sure it
  // still holds a numeric value and only acquire the last 2 numbers.
  // if it's not a string, nor an integer, we freak out and say no.
 
if(!is_int($o))
    if(
ctype_digit($o))
     
$o=(int)substr($o,-2,2);
    else
      return(
false);

 
// basically, if $o is between 11 and 19, we use 'th'
  // otherwise we use the last digit and if it's over
  // 4 then we use 0 (for the $s array index).
 
return($i.$s[($o%100>10&&$o%100<20)?0:($o%10<4?$o%10:0)]);
}

var_dump(ordinal(5));

/* Example Outputs of ordinal():
  0th, 1st, 2nd, 3rd, 4th, ..., 9th,
  10th, 11th, 12th, 13th, 14th, ..., 19th,
  110th, 111th, ..., 199th, 200th, 201st.

  ordinal('-1'); returns false because ctype_digit hates anything that
  isn't strictly 0 through 9 and '-' trips it to false.

  ordinal('asdf'); returns false for the exact same reason.

  ordinal(); returns false because it's blank.

  signed integers on a 32-bit system (and the same issue on a 64-bit
  system using 0x7FFFFFFFFFFFFFFF because of two's compliment,
  anything higher will become a negative number):
  ordinal(0x7FFFFFFF  ); returns 2147483647th (which is correct)
  ordinal(0x7FFFFFFF+1); returns false.
*/

?>
up
1
akam at akameng dor com
12 years ago
<?php
$d
= @$_GET['d'];

/*
assuming that passing value of d in the mysql
$sql = "select * from books where bookid = '$d' "
*/

/*
now check if $d is numeric?
*/

if(!is_numeric($d)){
$d = preg_replace("/[^0-9]+/", "", $d);
}
echo
"Cleared value: $d \n<br />Original Vlaue:".@$_GET['d'];
//then using clear value of $d in the mysql query
$sql = "select * from books where bookid = '$d' ";
?>
Example:
?d=52;d;s;s'2233l'[[22

Outpt:

Cleared value: 52223322
Original Vlaue:52;d;s;s'2233l'[[22
up
2
ben at chico dot com
10 years ago
Apparently NAN (Not A Number) is a number for the sake of is_numeric().

<?php
echo "is ";
if (!
is_numeric(NAN))
echo
"not ";
echo
"a number";
?>

Outputs "is a number". So something that is NOT a number (by defintion) is a number...
up
1
renimar no spam at nospam yahoo dot com
19 years ago
A little function to ordinalize numbers using is_numeric() and accounting for the numbers in the teens.

<?php
function ordinalize($num) {

        if (!
is_numeric($num))
                return
$num;

        if (
$num >= 11 and $num <= 19)
                return
$num."th";
        elseif (
$num % 10 == 1 )
                return
$num."st";
        elseif (
$num % 10 == 2 )
                return
$num."nd";
        elseif (
$num % 10 == 3 )
                return
$num."rd";
        else
                return
$num."th";

}

// Demo
for ($i=1; $i<=25; $i++) {
        print
ordinalize($i) . " ";
}

// The loop returns:
// 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th
// 13th 14th 15th 16th 17th 18th 19th 20th 21st 22nd
// 23rd 24th 25th

?>
up
1
lihatskiym at gmail dot com
8 years ago
Check that value is whole numeric or is whole integer.
<?php
function whole_numeric($val)
{
    if (
is_numeric($val)
        &&
floor($val) == $val)
    {
        if ((string)
$val === (string)0)
            return
true;
        elseif(
ltrim((string)$val, '0') === (string)$val)
            return
true;
    }

    return
false;
}

function
whole_int($val)
{
   
$val = strval($val);
   
$val = str_replace('-', '', $val);

    if (
ctype_digit($val))
    {
        if (
$val === (string)0)
            return
true;
        elseif(
ltrim($val, '0') === $val)
            return
true;
    }

    return
false;
}
?>

Result will be like this:

<?php
whole_numeric
('-1.0');  // true
whole_numeric(0);        // true
whole_numeric('0');      // true
whole_numeric('00');     // false
whole_numeric(1);        // true
whole_numeric('1');      // true
whole_numeric('1.0');    // true
whole_numeric('1,0');    // false
whole_numeric('1.2');    // false
whole_numeric('001');    // false
whole_numeric(array()); // false

whole_int('-1.0');    // false
whole_int('-1');       // true
whole_int(0);          // true
whole_int('0');        // true
whole_int('00');      // false
whole_int(1);          // true
whole_int('1');         // true
whole_int('1.0');      // false
whole_int('1.2');      // false
whole_int('001');     // false
whole_int(array()); // false
?>
up
1
jeffvanhees at gmail dot com
11 years ago
Function for checking all the values in an array for being numeric:

<?php
function is_numeric_array($array) {
    foreach (
$array as $key => $value) {
        if (!
is_numeric($value)) return false;
    }
    return
true;
}

$array_not_numeric = array('1', '2', 3, 'a'); // returns false
$array_numeric = array('1', '2', 3, 4); // returns true
?>
up
2
za at byza dot it
6 years ago
To check if a numeric string is a valid integer or float number:

function is_valid_number($a) {
   return $a==(float)$a && strlen($a)==strlen((float)$a);
}

This returns false for "0012345" and true for "0.12345"
up
1
sandreas
5 years ago
Note that strings with leading zeros containing only digits also return true on check with is_numeric, although they might be not a valid number. Example:

<?php
$x
= 009; // this is invalid php code, 009 is not octal
$y = 007; // this is valid php code, 007 is octal
$z = 01.12; // this also is valid php code

var_dump(is_numeric("009")); // outputs true
var_dump(is_numeric("007")); // outputs true
var_dump(is_numeric("00.12")); // outputs true
?>
up
1
Ray.Paseur sometimes uses Gmail
5 years ago
intval() appears to be helpful with hex strings:

<?php // is_hex_numeric.php
/**
* PHP 7.0.0+ Strings in hexadecimal (e.g. 0xf4c3b00c) notation
* are no longer regarded as numeric strings, i.e. is_numeric() returns FALSE now.
* See: http://php.net/manual/en/function.intval.php
*/
error_reporting(E_ALL);

var_dump( PHP_VERSION );              // string(6) "7.1.25"
var_dump( PHP_INT_SIZE );             // int(8)

$x = 0xf4c3b00c;                      // --> Assignment of hex value
var_dump($x);                         // int(4106465292)
var_dump( is_numeric($x) );           // bool(true)

$y = '0x' . dechex($x);               // --> Convert hex value to a string
var_dump($y);                         // string(10) "0xf4c3b00c"
var_dump( is_numeric($y) );           // bool(false)

$z = intval($y, 0);                   // --> intval() with base zero recognizes hex notation
var_dump($z);                         // int(4106465292)
var_dump( is_numeric($z) );           // bool(true)
var_dump($x == $z);                   // bool(true)
up
0
rds88
3 years ago
Notice that not only are leading spaces valid, but pretty much all whitespace characters and any combination thereof seems to be valid.

Examples (999 is the actual number), verified in PHP 7.3.x:

%09999 - a leading horizontal tabulator followed by the number
%20999 - a leading space followed by the number
%09%20999 - a leading tab, followed by a space, followed by the number
up
0
phil at kiwilimon dot com
5 years ago
There is another not documented big difference between PHP 5 and PHP 7:
is_numeric("45 "); // with a space at the end
will return true on PHP 5 and false on PHP 7
up
-1
orcinus
4 years ago
This page is a hot mess.

The changes note states:

“7.0.0    Strings in hexadecimal (e.g. 0xf4c3b00c) notation are no longer regarded as numeric strings, i.e. is_numeric() returns FALSE now.”

Meanwhile, the description says:

“Hexadecimal (e.g. 0xf4c3b00c) *and binary* (e.g. 0b10100111001) notation is not allowed.”

And finally, the examples section claims both are TRUE for is_binary.
What the hell?
up
0
Tim Robert-Fitzgerald
8 years ago
Be careful when using `is_numeric()` to validate user input and protect against SQL injection. According to wiki.hashphp.org,

"Many people reach for is_numeric() thinking this is a good approach, and it will seem to work just fine. However the problem with is_numeric() isn't that it can't detect an integer, it is that it detects a lot more than just integers. All of the following are valid numbers to is_numeric():

- 1
- 1.123
- 0xFF
- +0123.45e6

See the problem? If we really want just an integer, this function is too broad."

Source: http://wiki.hashphp.org/Validation#Why_is_numeric.28.29_is_bad
up
-1
cottton
7 years ago
As of http://php.net/manual/de/function.is-numeric.php#111709
' 12345' is considered numeric.

BUT '12345 ' NOT.

Test:
<?php
foreach (
    [
       
' 12345',
       
'12345 ',
       
' 12345 ',
    ] as
$value

) {
    echo
"'{$value}'\t" . var_export(is_numeric($value), true) . PHP_EOL;
}
/**
* Output:
*
*  ' 12345'        true
*  '12345 '        false
*  ' 12345 '       false
*/
?>
up
0
jsnell at e-normous dot com
10 years ago
Note that this function handles leading spaces differently than is_int(), is_float(), is_real(), is_long(), and is_double().

is_numeric(" 12345") = true
is_int(" 12345") = false
is_float(" 12345") = false
is_real(" 12345") = false
is_long(" 12345") = false
is_double(" 12345") = false
up
0
codeslinger at compsalot dot com
14 years ago
if speed is important, the liberal use of regex should be avoided, especially complex ones like those here.

For most purposes, this will be sufficient and has the advantages of both speed and clarity.

$BoolResult = empty(trim($Test, '+-.,0123456789'));

If the $Test contains any character that is not a valid part of a number the remaining string will not be empty.

if you want to be more restrictive of the '+-'  then you can use a separate trim for that and nest it.  Keep in mind that some notations pt the sign to the right of the number instead of to the left.  Depending upon your specific application you can also choose to ignore spaces and allow for 'e' notation.

I also use this approach when testing for other character sets such as Hex.
up
0
Magnus Deininger, dma05 at web dot de
15 years ago
regarding the global vs. american numeral notations, it should be noted that at least in japanese, numbers aren't grouped with an extra symbol every three digits, but rather every four digits (for example 1,0000 instead of 10.000). also nadim's regexen are slightly suboptimal at one point having an unescaped '.' operator, and the whole thing could easily be combined into a single regex (speed and all).

adjustments:

<?php
$eng_or_world
= preg_match
 
('/^[+-]?'. // start marker and sign prefix
 
'(((([0-9]+)|([0-9]{1,4}(,[0-9]{3,4})+)))?(\\.[0-9])?([0-9]*)|'. // american
 
'((([0-9]+)|([0-9]{1,4}(\\.[0-9]{3,4})+)))?(,[0-9])?([0-9]*))'. // world
 
'(e[0-9]+)?'. // exponent
 
'$/', // end marker
 
$str) == 1;
?>

i'm sure this still isn't optimal, but it should also cover japanese-style numerals and it fixed a couple of other issues with the other regexen. it also allows for an exponent suffix, the pre-decimal digits are optional and it enforces using either grouped or ungrouped integer parts. should be easier to trim to your liking too.
up
-3
james.holwell( at )exeter.ox.ac.uk
16 years ago
In reply to www.kigoobe.com, a more strict expression is

<?php
 
function my_is_numeric($value)
  {
    return (
preg_match ("/^(-){0,1}([0-9]+)(,[0-9][0-9][0-9])*([.][0-9]){0,1}([0-9]*)$/", $value) == 1);
  }
?>

This will not match strings like -6,77.8,8 which are matched by the below expression, and instead requires a single decimal point, with at least one character following, and only permits comma-separation when the right hand side is a triplet.
To Top