php check to see if variable is integer

Is there a nicer way to do this?

if( $_POST['id'] != (integer)$_POST['id'] )
    echo 'not a integer';

I’ve tried

if( !is_int($_POST['id']) )

But is_int() doesn’t work for some reason.

My form looks like this

<form method="post">
   <input type="text" name="id">
</form>

I’ve researched is_int(), and it seems that if

is_int('23'); // would return false (not what I want)
is_int(23);   // would return true

I’ve also tried is_numeric()

is_numeric('23'); // return true
is_numeric(23); // return true
is_numeric('23.3'); // also returns true (not what I want)

it seems that the only way to do this is:

if( '23' == (integer)'23' ) // return true
if( 23 == (integer)23 ) // return true
if( 23.3 == (integer)23.3 ) // return false
if( '23.3' == (integer)'23.3') // return false

But is there a function to do the above ?

Just to clarify, I want the following results

23     // return true
'23'   // return true
22.3   // return false
'23.3' // return false

Note: I just figured out my previous solution that I presented will return true for all strings. (thanks redreggae)

$var = 'hello';
if( $var != (integer)$var )
    echo 'not a integer';

// will return true! So this doesn't work either.

PHP: How to check if variable is a “large integer”

I need to check if a parameter (either string or int or float) is a large integer. By large integer I mean that it doesn’t have decimal places and can exceed PHP_INT_MAX. It’s used as msec timesta

Check if variable is a number and positive integer in PHP?

For example, say: <?php // Grab the ID from URL, e.g. example.com/?p=123 $post_id = $_GET[‘p’]; ?> How do I check if variable $post_id is a number, and a positive integer at that (i.e. 0-9, not

Check to see if string is an integer (includes negative numbers) PHP

The function below checks if a string is an integer meaning it should only contain digits. But it does not check if number is negative (negative numbers should return true as well since they are integ

How do I check to see if a value is an integer in MySQL?

I see that within MySQL there are Cast() and Convert() functions to create integers from values, but is there any way to check to see if a value is an integer? Something like is_int() in PHP is what I

Integer check in PHP

I’m writing an odds converter in PHP and came across this code for converting decimal odds to fractional ones function dec2frac($dec) { $decBase = –$dec; $div = 1; do { $div++; $dec = $decBase * $div

PHP: Compare Integer/String Variable with Null

I have an Integer/String variable. If I have an error in mysqli statement it becomes String and without errors it becomes number of affected rows (Integer). But in PHP if we have something like this:

Haskell: Check if integer, or check type of variable

So lets say you have a variable n. You want to check if its an integer, or even better yet check what type it is. I know there is a function in haskell, isDigit that checks if it is a char…However i

How to check if a variable is an integer?

I’m using Inno Setup and want to check with Pascal Script if a string variable is an Integer (0-9 only, no hex). I have made this funcion: function IsInt(s: string): boolean; var i, len: Integer; begi

PHP check if is integer

I have the following calculation: $this->count = float(44.28) $multiple = float(0.36) $calc = $this->count / $multiple; $calc = 44.28 / 0.36 = 123 Now I want to check if my variable $calc is in

How to constantly check a php variable?

I’m not sure if this is possible, but is there anyway you can constantly check the value of a variable in php to see if it is a certain value?

Answers

In PHP $_POST values are always text (string type).

You can force a variable into the integer type like this:

$int_id = (int)$_POST['id'];

That will work if you are certain that $_POST[‘id’] should be an integer. But if you want to make absolutely sure that it contains only numbers from 0 to 9 and no other signs or symbols use:

if( ctype_digit( $_POST['id'] ) )
{
  $int_id = (int)$_POST['id'];
}

Check it out: http://php.net/manual/en/function.ctype-digit.php – it validates if string contains only digits, so be sure not to pass an int to that function as it will most likely return false; However all values coming from $_POST are always strings so you are safe. Also it will not validate negative number such as -18 since – is not a digit, but you can always do ctype_digit(ltrim($number, ‘-‘))

is_int checks the variable type which in your case is string; it would be the same as (integer)$v === $v as == does some real obscure things in order to compare two variables of a different type; you should always use === unless you want mess like “0af5gbd” == 0 to return true

Also, keep in mind that ctype_digit will not tell you if the string can be actually converted to a valid int since maximum integer value is PHP_INT_MAX; If your value is bigger than that, you will get PHP_INT_MAX anyway.

try ctype_digit

if (!ctype_digit($_POST['id'])) {
    // contains non numeric characters
}

Note: It will only work with string types. So you have to cast to string your normal variables:

$var = 42;
$is_digit = ctype_digit((string)$var);

Also note: It doesn’t work with negative integers. If you need this you’ll have to go with regex. I found this for example:

EDIT: Thanks to LajosVeres, I’ve added the D modifier. So 123/n is not valid.

if (preg_match("/^-?[1-9][0-9]*$/D", $_POST['id'])) {
    echo 'String is a positive or negative integer.';
}

More: The simple test with casting will not work since “php” == 0 is true and “0” === 0 is false! See types comparisons table for that.

$var = 'php';
var_dump($var != (int)$var); // false

$var = '0';
var_dump($var !== (int)$var); // true

Check out the following link. http://php.net/manual/en/function.is-int.php

$num = 3;
$string = "some string";

if ( is_int($num) ) = returns true
if ( is_int($string) ) = returns false

if you’d like to see if the string is numeric use is_numeric($variable).

Hope that helps

preg_match('/^/d+$/D',$variable) //edit 

if you know it is a string variable (like post o get values), you can use:

function is_really_integer($var) {
  return $var == (string)(integer)$var;
}

try filter_var function

filter_var($_POST['id'], FILTER_VALIDATE_INT);

use:

if(filter_var($_POST['id'], FILTER_VALIDATE_INT)) { 
    //Doing sometihng...

}

The accepted answer using ctype_digit is correct, however you can make life easier using a function. This will covert the variable to a string, so you don’t have to:

function is_num($x){
    if(!is_string($x)){
        $x=(string)$x;
    }
    if(ctype_digit($x)){
      return true;
    }
    return false;
}

Usage:

if (is_num(56)) {
    // its a number
}

if (is_num('56')) {
    // its a number
}

If you want to accept decimals too, use this:

function is_num($x){
    if(!is_string($x)){
        $x=(string)$x;
    }    
    if (strpos($x,'.')!==false) {      
        if(substr_count($x,'.')>1||strpos($x,'.')<1||strpos($x,'.')>=strlen($x)){
            return false;    
        }
        $x=str_replace('.','',$x);    
    }
    if(ctype_digit($x)){
        return true;
    }  
    return false;
}

Use the following, universal function to check all types:

function is_digit($mixed) {
    if(is_int($mixed)) {
        return true;
    } elseif(is_string($mixed)) {
        return ctype_digit($mixed);
    }

    return false;
}

I use:

is_int($val)||ctype_digit($val)

Note than this catch only positive integer strings

Using is_numeric() for checking if a variable is an integer is a bad idea. This function will send TRUE for 3.14 for example. It’s not the expected behavior

To do this correctly, you can use one of these options :

Considering this variables array :

$variables = [
    "TEST 0" => 0,
    "TEST 1" => 42,
    "TEST 2" => 4.2,
    "TEST 3" => .42,
    "TEST 4" => 42.,
    "TEST 5" => "42",
    "TEST 6" => "a42",
    "TEST 7" => "42a",
    "TEST 8" => 0x24,
    "TEST 9" => 1337e0
];

The first option (FILTER_VALIDATE_INT Way) :

# Check if your variable is an integer
if( ! filter_var($variable, FILTER_VALIDATE_INT) ){
  echo "Your variable is not an integer";
}

Output :

TEST 0 : 0 (type:integer) is not an integer ✘
TEST 1 : 42 (type:integer) is an integer ✔
TEST 2 : 4.2 (type:double) is not an integer ✘
TEST 3 : 0.42 (type:double) is not an integer ✘
TEST 4 : 42 (type:double) is an integer ✔
TEST 5 : 42 (type:string) is an integer ✔
TEST 6 : a42 (type:string) is not an integer ✘
TEST 7 : 42a (type:string) is not an integer ✘
TEST 8 : 36 (type:integer) is an integer ✔
TEST 9 : 1337 (type:double) is an integer ✔

The second option (CASTING COMPARISON Way) :

# Check if your variable is an integer
if ( strval($variable) != strval(intval($variable)) ) {
  echo "Your variable is not an integer";
}

Output :

TEST 0 : 0 (type:integer) is an integer ✔
TEST 1 : 42 (type:integer) is an integer ✔
TEST 2 : 4.2 (type:double) is not an integer ✘
TEST 3 : 0.42 (type:double) is not an integer ✘
TEST 4 : 42 (type:double) is an integer ✔
TEST 5 : 42 (type:string) is an integer ✔
TEST 6 : a42 (type:string) is not an integer ✘
TEST 7 : 42a (type:string) is not an integer ✘
TEST 8 : 36 (type:integer) is an integer ✔
TEST 9 : 1337 (type:double) is an integer ✔

The third option (CTYPE_DIGIT Way) :

# Check if your variable is an integer
if( ! ctype_digit(strval($variable)) ){
  echo "Your variable is not an integer";
}

Output :

TEST 0 : 0 (type:integer) is an integer ✔
TEST 1 : 42 (type:integer) is an integer ✔
TEST 2 : 4.2 (type:double) is not an integer ✘
TEST 3 : 0.42 (type:double) is not an integer ✘
TEST 4 : 42 (type:double) is an integer ✔
TEST 5 : 42 (type:string) is an integer ✔
TEST 6 : a42 (type:string) is not an integer ✘
TEST 7 : 42a (type:string) is not an integer ✘
TEST 8 : 36 (type:integer) is an integer ✔
TEST 9 : 1337 (type:double) is an integer ✔

The fourth option (REGEX Way) :

# Check if your variable is an integer
if( ! preg_match('/^/d+$/', $variable) ){
  echo "Your variable is not an integer";
}

Output :

TEST 0 : 0 (type:integer) is an integer ✔
TEST 1 : 42 (type:integer) is an integer ✔
TEST 2 : 4.2 (type:double) is not an integer ✘
TEST 3 : 0.42 (type:double) is not an integer ✘
TEST 4 : 42 (type:double) is an integer ✔
TEST 5 : 42 (type:string) is an integer ✔
TEST 6 : a42 (type:string) is not an integer ✘
TEST 7 : 42a (type:string) is not an integer ✘
TEST 8 : 36 (type:integer) is an integer ✔
TEST 9 : 1337 (type:double) is an integer ✔

is_int is perfectly working there is not need of extra code

or you can check using is_numeric