PHP.mk документација

is_int

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.is-int.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.is-int.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
is_int

Референца за `function.is-int.php` со подобрена типографија и навигација.

function.is-int.php

is_int

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

is_intFind whether the type of a variable is integer

= NULL

is_int(mixed $value): bool

Проверете дали типот на променлива е цел број

Забелешка:

Проверува дали типот на дадената променлива е цел број. is_numeric().

Параметри

value

Променливата што се оценува.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true if value е int, false otherwise.

Примери

Пример #1 is_int() example

<?php
$values
= array(23, "23", 23.5, "23.5", null, true, false);
foreach (
$values as $value) {
echo
"is_int(";
var_export($value);
echo
") = ";
var_dump(is_int($value));
}
?>

Пример #1 Пример што покажува затворачка ознака што го опфаќа последниот нов ред

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)

Види Исто така

  • is_bool() - Дознајте дали променливата е булова
  • is_float() - Дознајте дали типот на променливата е float
  • is_numeric() - Дознајте дали променливата е број или нумерички стринг
  • is_string() - Finds whether a variable is a scalar
  • is_array() - Пронајдете дали променлива е низа
  • is_object() - Дознајте дали променливата е објект

Белешки од корисници 11 белешки

За да тестирате дали променлива е број или нумеричка низа (како внесување од форма, кое секогаш е низа), мора да користите
пред 17 години
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)
?>
Симон Нивс
пред 15 години
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
?>
Робин
пред 16 години
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).
e dot sand at elisand dot com
пред 9 години
Simon Neaves's answer is incomplete: negative integers will return false.

I recommend checking stackoverflow's answers:
http://stackoverflow.com/questions/6416763/checking-if-a-variable-is-an-integer-in-php
Хектор (hector-ordonez.com)
пред 15 години
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.

<?php
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
?>
andre dot roesti at 7flex dot net
пред 10 години
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. 

<?php 
if ( (int) $n !== $n ) { 
    echo 'not is int'; 
} else { 
    echo 'is int'; 
} 
?>
davide dot renzi at gmail dot com
пред 13 години
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) );
petepostma at gmail dot spam dot com
пред 13 години
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 :

<?php 
$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 :)
nicolas dot giraud at actiane dot com
пред 22 години
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.
gabe at websaviour dot com
пред 9 години
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;
}
?>
Василиј Макогон
пред 16 години
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+$.
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.