Главная | Руководство по MySQL | MySQL Manual | Документация к HTTP серверу Apache | Apache HTTP Server Documentation | downloads | faq

искать  Язык: Английский


is_int

(PHP 4, PHP 5)

is_intПроверяет, является ли переменная целого типа

Описание

bool is_int ( mixed $var )

Проверяет, является ли данная переменная целого типа.

Замечание: Чтобы проверить, что переменная является числом или числовой строкой (как поле ввода в форме, которое всегда является строкой), Вы должны использовать is_numeric().

Список параметров

var

Проверяемая переменная.

Возвращаемые значения

Возвращает TRUE, если var является целым числом, FALSE в противном случае.

Примеры

Пример #1 Пример использования is_int()

<?php
if (is_int(23)) {
 echo 
"целое число\n";
} else {
 echo 
"не целое число\n";
}
var_dump(is_int(23));
var_dump(is_int("23"));
var_dump(is_int(23.5));
var_dump(is_int(true));
?>

Результат выполнения данного примера:

целое число
bool(true)
bool(false)
bool(false)
bool(false)

Смотрите также

  • is_bool() - Проверяет, является ли переменная булевой
  • is_float() - Проверяет, является ли переменная числом с плавающей точкой
  • is_numeric() - Проверяет, является ли переменная числом или числовой строкой
  • is_string() - Проверяет, является ли переменная строкой
  • is_array() - Определяет, является ли переменная массивом
  • is_object() - Проверяет, является ли переменная объектом


User Contributed Notes
is_int
Robin
27-Mar-2010 04:22
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:

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

In a 64-bit environment:

<?php
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:

<?php
$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 environment

if( 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
?>
thierryreeuwijk at hotmail dot com
14-Jan-2010 10:04
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.

<?php

   
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)."<br>");
    print(
"15.5".int(15.5)."<br>");
    print(
"\"155\"".int("155")."<br>");
    print(
"\"15.5\"".int("15.5")."<br>");
    print(
"\"0155\"".int("0155")."<br>");
    print(
"\"I'm 155\"".int("I'm 155")."<br>");
    print(
"\"test\"".int("test")."<br>");
    print(
"\"\"".int(""));
?>

The above returns:

155        TRUE
15.5       FALSE
"155"      TRUE
"15.5"     FALSE
"0155"     TRUE
"I'm 155"  FALSE
"test"     FALSE
""         FALSE
dtp at rodanmedia dot net
04-Jan-2010 06:30
An interesting thing I discovered is that is_int() may not work if checking a string for only numeric values.

As a for instance, I have a form that requests user input, and the field name is $search.

When the user clicks the "submit" button, the form then runs through a couple of verifications, including one that checks whether they entered only numbers in the search (this is for those who specify searching by only a receipt number), not a hex code or some other alpha-numeric term.

When running ...
<?php
if (is_int($search)) {echo "Say something nice.";
}else{
echo
"Oops! You're no mathematician!";}
?>

... the script did not work. It read all entries, whether purely numeric or alpha-numeric, as non-integers.

In this case, "is_numeric" is precisely what is needed to verify whether the search is only a number. So the script becomes ...

<?php
if (is_numeric($search)) {echo "Say something nice.";
}else{
echo
"Oops! You're no mathematician!";}
?>

Just a noob's 'aha moment'.
me at rexxars dot com
16-Sep-2009 12:23
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:
<?php
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+$.
Roberto Rama
21-Jul-2009 06:39
Use this instead if you wanna know if a string is explicitly a number:

<?php

function isint( $mixed )
{
    return (
preg_match( '/^\d*$/'  , $mixed) == 1 );
}

var_export( isint( '123' ) ); //This will return true

var_export( isint( 123 ) ); //This will return true

var_export( isint( 'asd' ) ); //This will return false

var_export( isint( '123asd123' ) ); //This will return false

?>
corey at effim dot com
09-Jun-2009 08:21
If you're concerned with speed, you can save yourself about 50% of the time it takes to check whether or not something is an integer pretty easily...

Running through 10,000 iterations of each of the following 3 methods outputs fairly consistently...

<?php
$foo
= is_int($i);
// 0.0032429695129395 seconds

$foo = ((int) $i) == $i;
// 0.0020270347595215 seconds

$foo = ((int) $i) === $i;
// 0.001600980758667 seconds
?>

So if you want the best performance and know you're not going to be passed a string that needs to be typed as an integer, use === to compare the type as well.
Anonymous
03-Jun-2009 03:39
Typecasting will return false if a string has leading zeroes. If you prefer '023' return true, try:

<?php
function really_is_int($val)
{
    if(
func_num_args() !== 1)
        exit(
__FUNCTION__.'(): not passed 1 arg');

    return (
$val !== true) && ((string)abs((int) $val)) === ((string) ltrim($val, '-0'));
}
?>
e dot sand at elisand dot com
09-Apr-2009 03:27
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:

<?php
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).
leonix at motd dot ru
16-Dec-2008 08:08
another_is_int() is almost perfect, but it treats boolean true as int because
1 == (int) true == (string) true == '1'.

Fixed version:

<?php
/**
 * Checks if the given value represents integer
 */
function int_ok($val)
{
    return (
$val !== true) && ((string)(int) $val) === ((string) $val);
}
?>
paulo dot koch at g_mail dot com
17-Oct-2008 07:30
Don't over-engineer it.

<?php
function another_is_int($a){
    return ((string)
$a) === ((string)(int) $a);
}
?>
Wryel Covo - ryryel[at]gmail[dot]com
14-Oct-2008 06:53
<?php
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 "<br/>";
echo
onlyNumbers("xn89d9x797d9a8x7-"); //899797987
echo "<br/>";
if(
is_int($test)){
    echo
"Is int ! - �% inteiro !"; // This OK !
} else {
    echo
"Not int ! - N�_o �c inteiro";
}
?>
mark at codedesigner dot nl
26-Jun-2008 01:34
updated version from Simon Neaves

<?php
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
Julien Picalausa
11-May-2008 09:44
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
Simon Neaves
29-Apr-2008 06:14
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.

<?php
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)
?>
qlimmax at gmail dot com
07-Apr-2008 05:58
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",...)
wes9999 a myfastmail com
30-Nov-2007 05:28
a small modification to the isInt checks provided by lclkk at urbanvagabond dot net to make them work for scientific notation integers that are provided in string form:

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

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

Note the additional adding of 0 to $x in both functions.

This would allow the following tests to return true:
Test('53.45e2'); // 5345
Test('53.45e3'); // 53450

and this one to return false:
Test('53.45e1'); // 534.5
tudor at tudorholton dot com
05-Jul-2007 01:27
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)
Ender at soldat dot nl
16-Feb-2006 11:38
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.
ludvig dot ericson at gmail dot com
06-Jan-2006 09:00
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.)
<?php
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.
<?php
while (mySelect());
?>

Hope you get the point
 - toxik
lclkk at urbanvagabond dot net
16-Sep-2003 02:24
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);
?>
gabe at websaviour dot com
14-Jul-2003 06:08
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.
phpguru at gmx dot ch
05-Jul-2003 03:50
To Logan:

There's also a simple non-regexp way to convert a (form) value into an integer if it consists of numbers only - although with a trap (see below):

if ($_POST["number"] == (int)$_POST["number"]) $_POST["number"] = (int)$_POST["number"];

The "traps" (or "side effects") appear with values like "" (empty string) and false (boolean), which are converted to 0 (integer). But in certain cases this might be desirable or/and usefull ;-)

Solutions like

if (($_POST["number"] + 1 - 1) == $_POST["number"]) ...

falls into the same category.
mark at g33kz dot co dot uk
18-Jun-2003 12:44
Or you could just use is_numeric()

I have a file called input.php which I run at the beginning of all my scripts which makes sure all my input numbers are converted to integers automatically.

if ($_GET) {
  foreach ($_GET as $k => $v) {
    $_GET[$k] = trim (stripslashes ($v));
    if (is_numeric ($v)) {
      $_GET[$k] = intval ($v);
    }
  }
}
if ($_POST) {
  foreach ($_POST as $k => $v) {
    $_POST[$k] = trim (stripslashes ($v));
    if (is_numeric ($v)) {
      $_POST[$k] = intval ($v);
    }
  }
}
if ($_COOKIE) {
  foreach ($_COOKIE as $k => $v) {
    $_COOKIE[$k] = trim (stripslashes ($v));
    if (is_numeric ($v)) {
      $_COOKIE[$k] = intval ($v);
    }
  }
}
logan at logannet dot net
10-Feb-2003 11:42
[[Editors note: Or you can simply use is_numeric()]]

Some people have offered their ways to find out if a string from a form is an integer or not, here's my way:

if(ereg("^[0-9]+$", $_POST["number"])) $_POST["number"] = (int)$_POST["number"];

In psuedo code:
if you are a string full of numbers then convert yourself to an integer

So instead of just checking if its a string full of numbers you check and then convert it, which means you can use the standard is_int. You can also do:

if(ereg("^[0-9]+$", $_POST["number"])) $_POST["number"] += 0;

I think the first way i mentioned is better because your coding what you want to do, rather than the second way that uses a side effect of adding 0 to convert the string.

The first way also may make your code ever so slightly faster (nothing noticeable) as php does not need to add 0 to the number after it converts it.

Also note an integer is full numbers (1, 2, 3 etc) not decimal numbers (1.1, 2.4, 3.7 etc), to convert decimal numbers you could use something like:

if(ereg("^[.0-9]+$", $_POST["number"])) $_POST["number"] = (float)$_POST["number"];

OR

if(ereg("^[.0-9]+$", $_POST["number"])) $_POST["number"] += 0;

But note that these would not work with is_int(), because they are not integers.
 

 
credits | contact