略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: Integer 整型

2024-11-23

Integer 整型

int 是集合 ℤ = {..., -2, -1, 0, 1, 2, ...} 中的某个数。

参见:

语法

整型值 int 可以使用十进制,十六进制,八进制或二进制表示,前面可以加上可选的符号(- 或者 +)。 可以用 负运算符 来表示一个负的int

要使用八进制表达,数字前必须加上 0(零)。 PHP 8.1.0 起,八进制表达也可以在前面加上 0o 或者 0O 。 要使用十六进制表达,数字前必须加上 0x。要使用二进制表达,数字前必须加上 0b

从 PHP 7.4.0 开始,整型数值可能会包含下划线 (_),为了更好的阅读体验,这些下划线在展示的时候,会被 PHP 过滤掉。

示例 #1 整数文字表达

<?php
$a 
1234// 十进制数
$a 0123// 八进制数 (等于十进制 83)
$a 0o123// 八进制数 (PHP 8.1.0 起)
$a 0x1A// 十六进制数 (等于十进制 26)
$a 0b11111111// 二进制数字 (等于十进制 255)
$a 1_234_567// 整型数值 (PHP 7.4.0 以后)
?>

int 语法的结构形式是(PHP 7.4.0 之前不支持下划线):

decimal     : [1-9][0-9]*(_[0-9]+)*
            | 0

hexadecimal : 0[xX][0-9a-fA-F]+(_[0-9a-fA-F]+)*

octal       : 0[oO]?[0-7]+(_[0-7]+)*

binary      : 0[bB][01]+(_[01]+)*

integer     : decimal
            | hexadecimal
            | octal
            | binary

整型数 int 的字长和平台有关,尽管通常最大值是大约二十亿(32 位有符号)。64 位平台下的最大值通常是大约 9E18。 PHP 不支持无符号的 intint 值的字长可以用常量 PHP_INT_SIZE来表示, 最大值可以用常量 PHP_INT_MAX 来表示, 最小值可以用常量 PHP_INT_MIN 表示。

整数溢出

如果给定的一个数超出了 int 的范围,将会被解释为 float。同样如果执行的运算结果超出了 int 范围,也会返回 float

示例 #2 32 位系统下的整数溢出

<?php
$large_number 
2147483647;
var_dump($large_number);                     // int(2147483647)

$large_number 2147483648;
var_dump($large_number);                     // float(2147483648)

$million 1000000;
$large_number =  50000 $million;
var_dump($large_number);                     // float(50000000000)
?>

示例 #3 64 位系统下的整数溢出

<?php
$large_number 
9223372036854775807;
var_dump($large_number);                     // int(9223372036854775807)

$large_number 9223372036854775808;
var_dump($large_number);                     // float(9.2233720368548E+18)

$million 1000000;
$large_number =  50000000000000 $million;
var_dump($large_number);                     // float(5.0E+19)
?>

PHP 没有 int 除法取整运算符,要使用 intdiv() 实现。 1/2 产生出 float 0.5。 值可以舍弃小数部分,强制转换为 int,或者使用 round() 函数可以更好地进行四舍五入。

<?php
var_dump
(25/7);         // float(3.5714285714286) 
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7));  // float(4) 
?>

转换为整型

要明确地将一个值转换为 int,用 (int)(integer) 强制转换。不过大多数情况下都不需要强制转换,因为当运算符,函数或流程控制需要一个 int 参数时,值会自动转换。还可以通过函数 intval() 来将一个值转换成 int 整型。

resource 转换成 int 时, 结果会是 PHP 运行时为 resource 分配的唯一资源号。

参见:类型转换的判别

布尔值转换

false 将产生出 0(零),true 将产生出 1(壹)。

浮点型转换

当从浮点数 float 转换成整数 int 时,将向下取整。

如果浮点数超出了 int 范围(32 位平台下通常为 +/- 2.15e+9 = 2^31,64 位平台下,通常为 +/- 9.22e+18 = 2^63),则结果为未定义, 因为没有足够的精度给出一个确切的 int 结果。 在此情况下没有警告,甚至没有任何通知!

注意:

NaN 和 Infinity 在转换成 int 时是零。

警告

绝不要将未知的分数强制转换为 int,这样有时会导致不可预料的结果。

<?php
echo (int) ( (0.1+0.7) * 10 ); // 显示 7!
?>

参见关于浮点数精度的警告

从字符串转换

如果 string 是 numeric 或者前导数字, 则将它解析为相应的 int 值,否则将转换为零(0)。

NULL 转换

null 会转换为零(0)。

从其它类型转换

警告

没有定义从其它类型转换为 int 的行为。 不要依赖任何现有的行为,因为它会未加通知地改变。

add a noteadd a note

User Contributed Notes 25 notes

up
115
php at richardneill dot org
9 years ago
A leading zero in a numeric literal means "this is octal". But don't be confused: a leading zero in a string does not. Thus:
$x = 0123;          // 83
$y = "0123" + 0     // 123
up
48
d_n at NOSPAM dot Loryx dot com
14 years ago
Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters.

IP to BIGINT:
<?php
  $ipArr   
= explode('.',$_SERVER['REMOTE_ADDR']);
 
$ip       = $ipArr[0] * 0x1000000
           
+ $ipArr[1] * 0x10000
           
+ $ipArr[2] * 0x100
           
+ $ipArr[3]
            ;
?>

IP as BIGINT read from db back to dotted form:

Keep in mind, PHP integer operators are INTEGER -- not long. Also, since there is no integer divide in PHP, we save a couple of S-L-O-W floor (<division>)'s by doing bitshifts. We must use floor(/) for $ipArr[0] because though $ipVal is stored as a long value, $ipVal >> 24 will operate on a truncated, integer value of $ipVal! $ipVint is, however, a nice integer, so
we can enjoy the bitshifts.

<?php
        $ipVal
= $row['client_IP'];
       
$ipArr = array(0 =>
                   
floor$ipVal               / 0x1000000) );
       
$ipVint   = $ipVal-($ipArr[0]*0x1000000); // for clarity
       
$ipArr[1] = ($ipVint & 0xFF0000)  >> 16;
       
$ipArr[2] = ($ipVint & 0xFF00  )  >> 8;
       
$ipArr[3] =  $ipVint & 0xFF;
       
$ipDotted = implode('.', $ipArr);
?>
up
16
dhairya lakhera
4 years ago
-------------------------------------------------------------------------
Question :
var_dump((int) 010);  //Output 8

var_dump((int) "010"); //output 10

First one is octal notation so the output is correct. But what about the when converting "010" to integer. it should be also output 8 ?
--------------------------------------------------------------------------
Answer :

Casting to an integer using (int) will always cast to the default base, which is 10.

Casting a string to a number this way does not take into account the many ways of formatting an integer value in PHP (leading zero for base 8, leading "0x" for base 16, leading "0b" for base 2). It will simply look at the first characters in a string and convert them to a base 10 integer. Leading zeroes will be stripped off because they have no meaning in numerical values, so you will end up with the decimal value 10 for (int)"010".

Converting an integer value between bases using (int)010 will take into account the various ways of formatting an integer. A leading zero like in 010 means the number is in octal notation, using (int)010 will convert it to the decimal value 8 in base 10.

This is similar to how you use 0x10 to write in hexadecimal (base 16) notation. Using (int)0x10 will convert that to the base 10 decimal value 16, whereas using (int)"0x10" will end up with the decimal value 0: since the "x" is not a numerical value, anything after that will be ignored.

If you want to interpret the string "010" as an octal value, you need to instruct PHP to do so. intval("010", 8) will interpret the number in base 8 instead of the default base 10, and you will end up with the decimal value 8. You could also use octdec("010") to convert the octal string to the decimal value 8. Another option is to use base_convert("010", 8, 10) to explicitly convert the number "010" from base 8 to base 10, however this function will return the string "8" instead of the integer 8.

Casting a string to an integer follows the same the logic used by the intval function:

Returns the integer value of var, using the specified base for the conversion (the default is base 10).
intval allows specifying a different base as the second argument, whereas a straight cast operation does not, so using (int) will always treat a string as being in base 10.

php > var_export((int) "010");
10
php > var_export(intval("010"));
10
php > var_export(intval("010", 8));
8
up
4
ganlvtech at qq dot com
1 year ago
Be aware of float to int cast overflow

<?php

// You may expected these
var_dump(0x7fffffffffffffff);                // int(9223372036854775807)
var_dump(0x7fffffffffffffff + 1);            // float(9.2233720368548E+18)
var_dump((int)(0x7fffffffffffffff + 1));     // int(9223372036854775807)
var_dump(0x7fffffffffffffff + 1 > 0);        // bool(true)
var_dump((int)(0x7fffffffffffffff + 1) > 0); // bool(true)
var_dump((int)'9223372036854775807');        // int(9223372036854775807)
var_dump(9223372036854775808);               // float(9.2233720368548E+18)
var_dump((int)'9223372036854775808');        // int(9223372036854775807)
var_dump((int)9223372036854775808);          // int(9223372036854775807)

// But actually, it likes these
var_dump(0x7fffffffffffffff);                // int(9223372036854775807)
var_dump(0x7fffffffffffffff + 1);            // float(9.2233720368548E+18)
var_dump((int)(0x7fffffffffffffff + 1));     // int(-9223372036854775808)   <-----
var_dump(0x7fffffffffffffff + 1 > 0);        // bool(true)
var_dump((int)(0x7fffffffffffffff + 1) > 0); // bool(false)                 <-----
var_dump((int)'9223372036854775807');        // int(9223372036854775807)
var_dump(9223372036854775808);               // float(9.2233720368548E+18)
var_dump((int)'9223372036854775808');        // int(9223372036854775807)
var_dump((int)9223372036854775808);          // int(-9223372036854775808)   <-----

?>

These overflows are dangerous when you try to compare it with zero, or substract it from another value (e.g. money).
up
12
egwayjen at gmail dot com
4 years ago
"There is no integer division operator in PHP". But since PHP 7, there is the intdiv function.
up
13
rustamabd@gmail-you-know-what
15 years ago
Be careful with using the modulo operation on big numbers, it will cast a float argument to an int and may return wrong results. For example:
<?php
    $i
= 6887129852;
    echo
"i=$i\n";
    echo
"i%36=".($i%36)."\n";
    echo
"alternative i%36=".($i-floor($i/36)*36)."\n";
?>
Will output:
i=6.88713E+009
i%36=-24
alternative i%36=20
up
7
Anonymous
7 years ago
Converting to an integer works only if the input begins with a number
(int) "5txt" // will output the integer 5
(int) "before5txt" // will output the integer 0
(int) "53txt" // will output the integer 53
(int) "53txt534text" // will output the integer 53
up
8
Anonymous
15 years ago
To force the correct usage of 32-bit unsigned integer in some functions, just add '+0'  just before processing them.

for example
echo(dechex("2724838310"));
will print '7FFFFFFF'
but it should print 'A269BBA6'

When adding '+0' php will handle the 32bit unsigned integer
correctly
echo(dechex("2724838310"+0));
will print 'A269BBA6'
up
9
Anonymous
18 years ago
Sometimes you need to parse an unsigned
32 bit integer. Here's a function I 've used:
                                                                               
    function parse_unsigned_int($string) {
        $x = (float)$string;
        if ($x > (float)2147483647)
            $x -= (float)"4294967296";
        return (int)$x;
    }
up
3
litbai
6 years ago
<?php
$ipArr
= explode('.', $ipString);
$ipVal = ($ipArr[0] << 24)
       + (
$ipArr[1] << 16)
       + (
$ipArr[2] << 8)
       +
$ipArr[3]
        ;
?>
1. the priority of bit op is lower than '+',so there should be brackets.
2. there is no unsighed int in PHP, if you use 32 bit version,the code above will get negative result when the first position of IP string greater than 127.
3. what the code actually do is calculate the integer value of transformed 32 binary bit from IP string.
up
0
kuzawinski dot marcin_NOSPAM at gmail dot com
1 year ago
Integer literals may be decimal, octal, hexadecimal or binary, but integer values have single representation;

<?php

var_dump
(010); // int(8) NOT int(010)
var_dump(0x10); // int(16) NOT int(0x10)
var_dump(0b10); // int(2) NOT int(0b10)

?>

This is the reason why casting integer to string gives us always a decimal:

<?php

var_dump
((string) 010); // string(8) NOT string(010)
var_dump((string) 0x10); // string(16) NOT string(0x10)
var_dump((string) 0b10); // string(2) NOT string(0b10)

?>
up
4
darkshire
14 years ago
d_n at NOSPAM dot Loryx dot com
13-Aug-2007 05:33
Here are some tricks to convert from a "dotted" IP address to a LONG int, and backwards. This is very useful because accessing an IP addy in a database table is very much faster if it's stored as a BIGINT rather than in characters.

IP to BIGINT:
<?php
  $ipArr   
= explode('.',$_SERVER['REMOTE_ADDR']);
 
$ip       = $ipArr[0] * 0x1000000
           
+ $ipArr[1] * 0x10000
           
+ $ipArr[2] * 0x100
           
+ $ipArr[3]
            ;
?>

This can be written in a bit more efficient way:
<?php
  $ipArr   
= explode('.',$_SERVER['REMOTE_ADDR']);
 
$ip       = $ipArr[0]<<24
           
+ $ipArr[1]<<16
           
+ $ipArr[2] <<8
           
+ $ipArr[3]
            ;
?>

shift is more cheaper.
up
1
Jacek
15 years ago
On 64 bits machines max integer value is 0x7fffffffffffffff (9 223 372 036 854 775 807).
up
-12
eric
14 years ago
In response to the comment by me at troyswanson dot net:

-2147483648 falls into the range of 32 bit signed integers yet php treats it as a float.  However, -2147483647-1 is treated as an integer.

The following code demonstrates:
<?php
    var_dump
(-2147483648); //float(-2147483648)
   
var_dump(-2147483647 - 1); //int(-2147483648)
?>

This is probably very similar to the MS C bug which also treats -2147483648 as an UNSIGNED because it thinks it's out of the range of a signed int.

The problem is that the parser does not view "-x" as a single token, but rather as two, "-" and "x".  Since "x" is out of the range of an INT, it is promoted to float, even though in this unique case, "-x" is in the range of an int.

The best cure is probably to replace "-2147483648" with "0x80000000", as that is the hexadecimal equivalent of the same number.

Hope that helps explain what's going on

Peace

- Eric / fez
up
-14
pere dot cil at wanadoo dot fr
11 years ago
Please also note that the maximum stored in the integer depends on the platform / compilation; on windows xp 32 bits, the following value:

0x5468792130ABCDEF

echoes to:

6.0822444802213E+18 (cast to float)

On a fully 64 bits system, it echoes to:

6082244480221302255
up
-14
wbcarts at juno dot com
13 years ago
PHP offers a slew of built-in functions and automatic type-casting routines which can get pretty complicated. But most of the time, you still have to take matters into your own hands and allow PHP to do its thing. In that case, and something that has NOT been mentioned, is how to construct your code. To keep things simple, I divide all my scripts in half. The top half gives my scripts the "capability" they need, and the lower half is the actual code to be "run" or "executed".

<?php
/*
* build the program's capability - define variables and functions...
*/
$item_label = '';        // type string
$item_price = 0.0;       // type float
$item_qty = 1;           // type integer
$item_total = 0.0;       // type float - to set use calculate()

function calculate(){
  global
$item_price, $item_qty, $item_total;
 
$item_price = number_format($item_price, 2);
 
$item_total = number_format(($item_price * $item_qty), 2);
}

function
itemToString() {
  global
$item_label, $item_price, $item_qty, $item_total;
  return
"$item_label [price=\$$item_price, qty=$item_qty, total=\$$item_total]";
}

/*
* run the program - set data, call methods...
*/
$item_label = "Coffee";
$item_price = 3.89;
$item_qty = 2;
calculate();           // set $item_total
echo itemToString();   // -> Coffee [price=$3.89, qty=2, total=$7.78]

$item_label = "Chicken";
$item_price = .80;     // per lb.
$item_qty = 3.5;       // lbs.
calculate();           // set $item_total
echo itemToString();   // -> Chicken [price=$0.80, qty=3.5, total=$2.80]
?>
Note: All type-casting is done by PHP's built-in number_format() method. This allows our program to enter any number (float or int) on item price or quantity in the runtime part of our script. Also, if we explicitly cast values to integer in the capability part of our script, then we start getting results that may not be desirable for this program. For example, if in the calculate method we cast item_qty to integer, then we can no longer sell chicken by the pound!
up
-11
dewi at dewimorgan dot com
7 years ago
Note that the soft-typing of numbers in PHP means that some things become very difficult. For example, efficiently emulating the more common linear congruential generators (LCGs) for fast, deterministic, pseudo-randomness. The naive code to create the next value in a sequence (for power-of-2 values of $m) is:

$seed = ($seed * $a + $c) % $m;

...where $m, $a, and $c are values and data types carefully chosen such that repeating this operation will eventually generate every value in the range $0 to $m, with no repetition.

I can find no good commonly used LCGs which use PHP-compatible values. The LCG values used in by rand() in systems like Borland Delphi, Virtual Pascal, MS Visual/Quick C/C++, VMS's MTH$RANDOM, old versions of glibc, Numerical Recipes, glibc, GCC, ANSI C, Watcom, Digital Mars, CodeWarrior, IBM VisualAge C/C++, java.util.Random, Newlib, MMX... *all* fail when ported, for one of two reasons, and sometimes both:

- In PHP on 32 bit machines and all Windows machines, $m = 2^32 or larger requires UInt or even UInt64, or the result becomes negative.

- Large $a multiplied by an integer seed gets converted to a float64, but the number can be too long for the 53-bit mantissa, and it drops the least significant digits... but the LCG code above requires that the most significant digits should be lost.

These are two classes of problem to beware of when porting integer math to PHP,  and I see no clean and efficient way to avoid either one.

So if designing a cross-platform system that must work in PHP, you must select LCG values that fit the following criteria:
$m = 2^31 or less (PHP limitation). Recommend: 2^31.
$a = Less than 2^22 (PHP limitation); $a-1 divisible by all prime factors of $m; $a-1 divisible by 4 if $m is. Recommend: 1+(4*(any prime <= 1048573)).
$c = smaller than (2^53-($m*$a)) (PHP limitation); relatively prime with $m. Recommend: any prime <= 23622320123.
up
-9
13453814063 at 163 dot com
4 years ago
$e = 0x8000000000000000;
$e2 = 0b1000000000000000000000000000000000000000000000000000000000000000;
if ($e == $e2){
    echo "e==e2<br>";
}else{
    echo "e!=e2<br>";
}
pirnt "e!=e2"
----------------------------
echo decbin($e) . "<br>";
echo decbin($e2) . "<br>";
the result is :
1000000000000000000000000000000000000000000000000000000000000000
111111111111111111111111111111111111111111111111111110000000000
up
-19
popefelix at gmail dot com
15 years ago
Be careful when using integer conversion to test something to see if it evaluates to a positive integer or not.  You might get unexpected behaviour.

To wit:
<?php
error_reporting
(E_ALL);
require_once
'Date.php';

$date = new Date();
print
"\$date is an instance of " . get_class($date) . "\n";
$date += 0;
print
"\$date is now $date\n";
var_dump($date);

$foo = new foo();
print
"\$foo is an instance of " . get_class($foo) . "\n";
$foo += 0;
print
"\$foo is now $foo\n";
var_dump($foo);

class
foo {
    var
$bar = 0;
    var
$baz = "la lal la";
    var
$bak;

    function
foo() {
       
$bak = 3.14159;
    }
}
?>

After the integer conversion, you might expect both $foo and $date to evaluate to 0.  However, this is not the case:

$date is an instance of Date

Notice: Object of class Date could not be converted to int in /home/kpeters/work/sketches/ObjectSketch.php on line 7
$date is now 1
int(1)
$foo is an instance of foo

Notice: Object of class foo could not be converted to int in /home/kpeters/work/sketches/ObjectSketch.php on line 13
$foo is now 1
int(1)

This is because the objects are first converted to boolean before being converted to int.
up
-25
jmw254 at cornell dot edu
15 years ago
Try this one instead:

function iplongtostring($ip)
{
    $ip=floatval($ip); // otherwise it is capped at 127.255.255.255

    $a=($ip>>24)&255;
    $b=($ip>>16)&255;
    $c=($ip>>8)&255;
    $d=$ip&255;

    return "$a.$b.$c.$d";
}
up
-25
rickard_cedergren at yahoo dot com
17 years ago
When doing large subtractions on 32 bit unsigned integers the result sometimes end up negative. My example script converts a IPv4 address represented as a 32 bit unsigned integer to a dotted quad (similar to ip2long()), and adds a "fix" to the operation.

   /**************************
    * int_oct($ip)
    * Convert INTeger rep of IP to octal (dotted quad)
    */
   function int_oct($ip) {

      /* Set variable to float */
      settype($ip, float);

      /* FIX for silly PHP integer syndrome */
      $fix = 0;
      if($ip > 2147483647) $fix = 16777216;

      if(is_numeric($ip)) {
         return(sprintf("%u.%u.%u.%u",
                $ip / 16777216,
                (($ip % 16777216) + $fix) / 65536,
                (($ip % 65536) + $fix / 256) / 256,
                ($ip % 256) + $fix / 256 / 256
                )
     );
      }
      else {
         return('');
      }
   }
up
-27
php at keith tyler dot com
11 years ago
If you need to convert a numeric string (or more to the point, an object that represents a numeric value) that is greater then PHP_INT_MAX, and you don't have GMP or BCMath installed, you can cast to float.

For example, when using SimpleXMLElement, you sometimes have to cast the extracted values, such as xml attributes, because they are returned as SimpleXMLElements and not their values' native types. While print() has no trouble with converting them, other functions, such as max(), might not.

But if you cast such a value with (int), and it is over PHP_INT_MAX, you will just get PHP_INT_MAX (and vice versa for negative numbers).

The Q&D no-muss solution is to cast to (float) instead.
up
-34
sean dot gilbertson at gmail dot com
13 years ago
You can make a signed, negative integer an unsigned integer (in string form) by doing the following:

<?php
$unsigned
= sprintf('%u', -5);

echo
$unsigned; // prints 4294967291
?>
up
-35
Hamza Burak Ylmaz
13 years ago
<?php
//This is a simple function to return number of digits of an integer.

//function declaration
function count_digit($number)
{
   
$digit = 0;
    do
    {
       
$number /= 10;      //$number = $number / 10;
       
$number = intval($number);
       
$digit++;   
    }while(
$number!=0);
    return
$digit;
}

//function call
$num = 12312;
$number_of_digits = count_digit($num); //this is call :)
echo $number_of_digits;
//prints 5
?>
up
-53
Richard
11 years ago
Integer arithmetic in PHP is more accurate than one might think. On a 32-bit system, the largest value that can be held in an INT is  2147483647.
However, a FLOAT can accurately hold integer values up to 10000000000000.
(this is because the significand precision of a double is 53-bits).

官方地址:https://www.php.net/manual/en/language.types.integer.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3