How do you check if a number is int or float in php?

Artefacto's answer will also convert a 5.0 float number into a 5 integer. If that is bugging you like it was bugging me, I offer the answer of automatic type conversion via the multiplication operator:

If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as ints, and the result will also be an int.

$demo = array(
    1, 2, 3, '1', '2', '3', 
    1.0, 2.1, 3.2, '1.0', '2.1', '3.2', 
    -17, '-17', 
    -1.0, -2.2, '-1.0', '-2.2',
    0, '0', -0, '-0',
    0.0, '0.0', -0.0, '-0.0',
);

foreach ($demo as $k => $v) {
    if (is_numeric($v) && is_string($v)) {
        $demo[$k] = 1 * $v;
    }
}

echo "
"; var_dump($demo); echo "
"; array(26) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(1) [4]=> int(2) [5]=> int(3) [6]=> float(1) [7]=> float(2.1) [8]=> float(3.2) [9]=> float(1) [10]=> float(2.1) [11]=> float(3.2) [12]=> int(-17) [13]=> int(-17) [14]=> float(-1) [15]=> float(-2.2) [16]=> float(-1) [17]=> float(-2.2) [18]=> int(0) [19]=> int(0) [20]=> int(0) [21]=> int(0) [22]=> float(0) [23]=> float(0) [24]=> float(-0) [25]=> float(-0) }

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

is_intFind whether the type of a variable is integer

Description

is_int(mixed $value): bool

Note:

To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use is_numeric().

Parameters

value

The variable being evaluated.

Return Values

Returns true if value is an int, false otherwise.

Examples

Example #1 is_int() example

$values = array(23"23"23.5"23.5"nulltruefalse);
foreach (
$values as $value) {
    echo 
"is_int(";
    
var_export($value);
    echo 
") = ";
    
var_dump(is_int($value));
}
?>

The above example will output:

is_int(23) = bool(true)
is_int('23') = bool(false)
is_int(23.5) = bool(false)
is_int('23.5') = bool(false)
is_int(NULL) = bool(false)
is_int(true) = bool(false)
is_int(false) = bool(false)

See Also

  • is_bool() - Finds out whether a variable is a boolean
  • is_float() - Finds whether the type of a variable is float
  • is_numeric() - Finds whether a variable is a number or a numeric string
  • is_string() - Find whether the type of a variable is string
  • is_array() - Finds whether a variable is an array
  • is_object() - Finds whether a variable is an object

Simon Neaves

14 years ago

I've found that both that is_int and ctype_digit don't behave quite as I'd expect, so I made a simple function called isInteger which does. I hope somebody finds it useful.

function isInteger($input){
    return(
ctype_digit(strval($input)));
}
var_dump(is_int(23)); //bool(true)
var_dump(is_int("23")); //bool(false)
var_dump(is_int(23.5)); //bool(false)
var_dump(is_int(NULL)); //bool(false)
var_dump(is_int("")); //bool(false)var_dump(ctype_digit(23)); //bool(true)
var_dump(ctype_digit("23")); //bool(false)
var_dump(ctype_digit(23.5)); //bool(false)
var_dump(ctype_digit(NULL)); //bool(false)
var_dump(ctype_digit("")); //bool(true)var_dump(isInteger(23)); //bool(true)
var_dump(isInteger("23")); //bool(true)
var_dump(isInteger(23.5)); //bool(false)
var_dump(isInteger(NULL)); //bool(false)
var_dump(isInteger("")); //bool(false)
?>

Robin

12 years ago

Keep in mind that is_int() operates in signed fashion, not unsigned, and is limited to the word size of the environment php is running in.

In a 32-bit environment:

is_int( 2147483647 );           // true
is_int( 2147483648 );           // false
is_int( 9223372036854775807 );  // false
is_int( 9223372036854775808 );  // false
?>

In a 64-bit environment:

is_int( 2147483647 );           // true
is_int( 2147483648 );           // true
is_int( 9223372036854775807 );  // true
is_int( 9223372036854775808 );  // false
?>

If you find yourself deployed in a 32-bit environment where you are required to deal with numeric confirmation of integers (and integers only) potentially breaching the 32-bit span, you can combine is_int() with is_float() to guarantee a cover of the full, signed 64-bit span:

$small = 2147483647;         // will always be true for is_int(), but never for is_float()
$big = 9223372036854775807// will only be true for is_int() in a 64-bit environmentif( is_int($small) || is_float($small) );  // passes in a 32-bit environment
if( is_int($big) || is_float($big) );      // passes in a 32-bit environment
?>

e dot sand at elisand dot com

13 years ago

Simon Neaves was close on explaining why his function is perfect choice for testing for an int (as possibly most people would need).  He made some errors on his ctype_digit() output though - possibly a typo, or maybe a bug in his version of PHP at the time.

The correct output for parts of his examples should be:

var_dump(ctype_digit(23)); //bool(false)
var_dump(ctype_digit("23")); //bool(true)
var_dump(ctype_digit(23.5)); //bool(false)
var_dump(ctype_digit(NULL)); //bool(false)
var_dump(ctype_digit("")); //bool(false)
?>

As you can see, the reason why using *just* ctype_digit() may not always work is because it only returns TRUE when given a string as input - given a number value and it returns FALSE (which may be unexpected).

andre dot roesti at 7flex dot net

12 years ago

With this function you can check if every of multiple variables are int. This is a little more comfortable than writing 'is_int' for every variable you've got.

function are_int ( ) {
   
$args = func_get_args ();
    foreach (
$args as $arg )
        if ( !
is_int ( $arg ) )
            return
false;
    return
true;
}
// Example:
are_int ( 4, 9 ); // true
are_int ( 22, 08, 'foo' ); // false
?>

davide dot renzi at gmail dot com

6 years ago

I've found a faster way of determining an integer.
On my env, this method takes about half the time of using is_int().

Cast the value then check if it is identical to the original.

if ( (int) $n !== $n ) {
    echo
'not is int';
} else {
    echo
'is int';
}
?>

petepostma at gmail dot spam dot com

10 years ago

There is a versa to the vice of this int only type check.

is_int( $integer_type) will only return true, if the TYPE is int, not the value
ctype_digit( $string_type) will only return true if the TYPE is string, and its value is INT

therefore:
return ( is_int($value) || ctype_digit($value) );

nicolas dot giraud at actiane dot com

10 years ago

Just a shorter way to check if your variable is an int or a string containing a int without others digit than 0 to 9 :

$bool = ( !is_int($value) ? (ctype_digit($value)) : true );$value = 42; //true
$value = '42'; //true
$value = '1e9'; //false
$value = '0155'; //true
$value = 0155; //true
$value = 0xFF; //true while it's just the same as 255
$value = '0xFF'; //false
$value = 'a'; //false
$value = array(); //false
$value = array('5'); //false
$value = array(5); false
$value
= ''; //false
$value = NULL; //false?>

Short & cool :)

Vasiliy Makogon

6 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:

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;
}
?>

gabe at websaviour dot com

19 years ago

Although this can be inferred from the documentation, beware of numeric strings.  I ran into the problem in a MySQL app where I would either SELECT an INT PRIMARY KEY or INSERT a new record and use mysql_insert_id() to get the KEY before continuing onto the new section. 

I used is_int() to make sure the subsequent queries wouldn't break when using the key variable.  Unfortunately I failed to realize that while mysql_insert_id() returns an int, mysql_result() always returns a string even if you are SELECTing from an INT field.

Spent at least 30 minutes trying to figure out why existing records weren't getting linked, but new records would link fine.  I ended up using intval() on mysql_result() to make sure subsequent queries still always work.

me at rexxars dot com

13 years ago

I was looking for the fastest way to check for an unsigned integer which supported large numbers like 4318943448871348 or 0xFFFFFFFF.

Fastest I came up with is this:
function is_unsigned_int($val) {
    return
ctype_digit((string) $value));
}
?>

Will return true on 1515, 0xFFFFFFFF, '3515' and '1365158185855141'.
Will return false on 0.1515, '415.4134' and '-616'.

Be aware though, before PHP 5.1.0 this will return true on an empty string.

According to my benchmarks this is about 30% faster than the regex ^\d+$.

tudor at tudorholton dot com

15 years ago

Please note this from the Integer datatype page:

"The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined from PHP_INT_SIZE, maximum value from PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5."

This is particularly important if you are doing validation of large keys or any number larger than 2,000,000,000 (e.g. telephone numbers)

Julien Picalausa

14 years ago

To check if a string ($s) is a representation of an integer (including representations is scientific notation and negative numbers), you can use the following test, provided that you don't expect values that are out of bounds for an integer.

is_numeric($s) && floatval($s) == intval(floatval($s))

If the test returns true, the string is a representation of an integer.
is_numeric (if it works as intended) protects from strings that are not proper numbers.
The comparison filters anything that is non_integer

If, for performance reasons, you want to avoid converting to float twice, it can also be written:
is_numeric($s) && ($f = floatval($s)) == intval($f)

If you plan to get values that cannot be representated with an integer and are ready to deal with a float, you can use floor instead of intval, as long as you are ready to deal with floats. Even so, that method will become unreliable when the precision of the float becomes insufficient for getting to the fractional part of the number

ludvig dot ericson at gmail dot com

16 years ago

I would like to say that is_int() is pretty helpfull when looking for neat proper ways to check functions that return either integers or booleans (false) on failure (strpos, socket_select, etc.)
function mySelect() {
    global
$someSockets;
   
$ret = socket_select($someSockets, $o = array(), $e = array(), 0);
    if (!
$ret)
        return
is_int($ret);
   
/* FURTHER PROCESSING HERE */
   
return true;    // Return true if the function proceeded as expected.
}
?>
The point of doing this is that if you put this in a while() loopo, you'll break it when the select fails.
while (mySelect());
?>

Hope you get the point
- toxik

lksunny at live dot hk

5 years ago

function check_num($num){
    if (preg_match("#^(-[0-9]{1,}|[0-9]{1,})$#", $num)){
        return true;
    }else{
        return false;
    }
}
var_dump(-1); //True
var_dump("-1"); //True
var_dump("1"); //True
var_dump("-999999999999999999"); //True
var_dump("999999999999999999"); //True
?>

negative number will be true :)

qlimmax at gmail dot com

14 years ago

function is_natural($natural,$zero=true)
{
if(ctype_digit($natural))
{
    if($zero)
    {
        $natural_test=(int)$natural;
        if((string)$natural_test !== $natural) return false;
        else return true;
    }
    else return true;
}
else return false;   
}

true for ("0","1","2","3",...) false for("-1","01","adS","#@!$%^&*-...","0.7","0,7", "0x12",...)
if $zero=false
true for("0","00","1","01",...) false("-1","#@!$%^&*-...","adS","0.7","0,7", "0x12",...)

Ender at soldat dot nl

16 years ago

Be aware that is_numeric (mentioned in this article as the proper way to validate string numbers) also allows numbers in scientific and hexadecimal annotation. Thus DO NOT USE that function to validate user input that will be used as id number for in a query for example, this could cause mysql errors. Use ctype_digit instead.

lclkk at urbanvagabond dot net

19 years ago

I think the function below is a robust test for integers working on all datatypes. It works by first checking that a number can be evaluated numerically, and then secondly that the integer evaluation matches the original number.

Test cases are included.

function myIsInt ($x) {
    return (is_numeric($x) ? intval($x) == $x : false);
}

function Test($x) {
    echo "$x is " . ( myIsInt($x) ? ('an integer. The integer value is ' . intval($x)) : 'not an integer.');
    echo "\n";
}

echo "These should be integers...\n";
Test(1);
Test(5);
Test(10);
Test(10.0);
Test(20.0);
Test(-20.0);
Test(0+4+4.5+4.5);
Test("10.0");
Test("+14");
Test("-15");
Test("0");

echo "\nThese should not be integers...\n";
Test(true); // watch out, this displays as '1'
Test(false);
Test("moose");
Test("3.5");
Test("-214235.5");
Test(""); // empty string
Test(array(1,2,3));
Test(dir('.')); // object
Test(null);
?>

PHPDev esurf er s >dot

7 years ago

This will check if something has an acceptable integer value, such as

a string with int value like "1" or "1.0"
a float with int value like 1.0
an int like 12e5

The same as is_numeric, but with integer values.

function isIntValued($var) {
        if(
is_numeric($var)) {
           
$var=(float)$var;
            return ((float)(int)
$var)===$var;
        }
        return
FALSE;
    }
?>

Wryel Covo - ryryel[at]gmail[dot]com

13 years ago

function onlyNumbers($string){
   
//This function removes all characters other than numbers
    //Esta função limpa a url e conserva apenas os numeros
   
$string = preg_replace("/[^0-9]/", "", $string);
    return (int)
$string;
}

echo

$test = onlyNumbers("as87d68a6db8a7d686dx8a6dx"); //2147483647
echo "
"
;
echo
onlyNumbers("xn89d9x797d9a8x7-"); //899797987
echo "
"
;
if(
is_int($test)){
    echo
"Is int ! - É inteiro !"; // This OK !
} else {
    echo
"Not int ! - Não é inteiro";
}
?>

mark at codedesigner dot nl

14 years ago

updated version from Simon Neaves

function isInteger($input){
  return
preg_match('@^[-]?[0-9]+$@',$input) === 1;
}
?>

this function checks if the string:
- starts with a - sign (optional)
- ends with 1 or more numeric chars

ing dot alpi at gmail dot com

9 years ago

Remember that some source of data always give a string data type.
That's the case with cookies and $_GET.
if you need to check against those values, try to convert them into numbers first.
The easiest way of doing so is adding a zero before your var, just like:

$var = '15'; // ...or $var = $_COOKIE['myvar'] or $var =
$_GET['myvar']...is_int($var);  // now returns FALSE$var += 0;is_int($var);  // now returns TRUE
?>

leonix at motd dot ru

13 years ago

another_is_int() is almost perfect, but it treats boolean true as int because
1 == (int) true == (string) true == '1'.

Fixed version:

/**
* Checks if the given value represents integer
*/
function int_ok($val)
{
    return (
$val !== true) && ((string)(int) $val) === ((string) $val);
}
?>

arturs at indigo dot lv

10 years ago

Sometime needed check if string containing numbers is integer or not. Then I created this small function:
function is_integer2($v) {
 
$i = intval($v);
  if (
"$i" == "$v") {
    return
TRUE;
  } else {
    return
FALSE;
  }
}
?>

Roberto Rama

13 years ago

Use this instead if you wanna know if a string is explicitly a number:

function isint( $mixed )
{
    return (
preg_match( '/^\d*$/'  , $mixed) == 1 );
}
var_export( isint( '123' ) ); //This will return truevar_export( isint( 123 ) ); //This will return truevar_export( isint( 'asd' ) ); //This will return falsevar_export( isint( '123asd123' ) ); //This will return false?>

some at somewhere dot com

9 years ago

// check if input is a valid number
// first number must be 1 thru 9, followed by a number 0-9, no decimals
// true for "1", "1000"
// false for "01", "-1", "1.2"
function isInteger($input){
  return
preg_match('@^[1-9][0-9]*$@',$input) === 1;
}
?>

thierryreeuwijk at hotmail dot com

12 years ago

If you only want integer values like 23 or 0155, or form/string integer values like "23" or "0155" to be valid, this should work just fine.

function int($int){// First check if it's a numeric value as either a string or number
       
if(is_numeric($int) === TRUE){// It's a number, but it has to be an integer
           
if((int)$int == $int){

                return

TRUE;// It's a number, but not an integer, so we fail
           
}else{

                            return

FALSE;
            }
// Not a number
       
}else{

                    return

FALSE;
        }
    }

    print(

"155".int(155)."
"
);
    print(
"15.5".int(15.5)."
"
);
    print(
"\"155\"".int("155")."
"
);
    print(
"\"15.5\"".int("15.5")."
"
);
    print(
"\"0155\"".int("0155")."
"
);
    print(
"\"I'm 155\"".int("I'm 155")."
"
);
    print(
"\"test\"".int("test")."
"
);
    print(
"\"\"".int(""));
?>

The above returns:

155        TRUE
15.5       FALSE
"155"      TRUE
"15.5"     FALSE
"0155"     TRUE
"I'm 155"  FALSE
"test"     FALSE
""         FALSE

Anonymous

7 years ago

Sometimes, we need to validate if a DECIMAL returned by a SQL database is an int or not. DECIMAL always return .000 at end of the string.

Then i use:
function isInteger($input){
{
    if(
strpos($input,"."))
       
$input=preg_replace("/\.$/","",rtrim(strval($input),"0"));
    return (
ctype_digit($input));
}
?>

felix dot b at outlook dot com

7 years ago

((int)$foo === $foo) does exactly the same as is_int($foo), but is faster performancewise, because PHP has quite an overhead on function calls.

As you can see the expression only returns true if the type (and value) of $foo is the same as int-casted $foo, which is only the case when foo is an int.

This applies to all the other is* functions aswell.

How do you know if a number is int or float?

Use the isinstance() function to check if a number is an int or float, e.g. if isinstance(my_num, int): . The isinstance function will return True if the passed in object is an instance of the provided class ( int or float ).

How do you check if a number is an integer in PHP?

The is_int() function checks whether a variable is of type integer or not. This function returns true (1) if the variable is of type integer, otherwise it returns false.

How do you check if a value is float or not?

Check if the value has a type of number and is not an integer. Check if the value is not NaN . If a value is a number, is not NaN and is not an integer, then it's a float.

How do you check if a value is an integer or string in PHP?

The is_numeric() function checks whether a variable is a number or a numeric string. This function returns true (1) if the variable is a number or a numeric string, otherwise it returns false/nothing.