Целые

Целое это число из множества Z = {..., -2, -1, 0, 1, 2, ...}.

Смотрите также: Целые произвольной длины / GMP, Числа с плавающей точкой и Произвольная точность / BCMath

Синтаксис

Целые могут быть указаны в десятичной, шестнадцатеричной или восьмеричной системе счисления, по желанию с предшествующим знаком (- или +).

Если вы используете восьмеричную систему счисления, вы должны предварить число 0 (нулем), для использования шестнадцатеричной системы нужно поставить перед числом 0x.

Пример #1 Целые

<?php
$a 
1234// десятичное число
$a = -123// отрицательное число
$a 0123// восьмеричное число (эквивалентно 83 в десятичной системе)
$a 0x1A// шестнадцатеричное число (эквивалентно 26 в десятичной системе)
?>
Формально возможная структура целых такова:
десятичные        : [1-9][0-9]*
                  | 0

шестнадцатеричные : 0[xX][0-9a-fA-F]+

восьмеричные      : 0[0-7]+

целые             : [+-]?десятичные
                  | [+-]?шестнадцатеричные
                  | [+-]?восьмеричные
Размер целого зависит от платформы, хотя, как правило, максимальное значение около двух миллиардов (это 32-битное знаковое). PHP не поддерживает беззнаковые целые.

Превышение размера целого

Если вы определите число, превышающее пределы целого типа, оно будет интерпретировано как число с плавающей точкой. Также, если вы используете оператор, результатом работы которого будет число, превышающее пределы целого, вместо него будет возвращено число с плавающей точкой.

<?php
$large_number 
=  2147483647;
var_dump($large_number);
// вывод: int(2147483647)

$large_number =  2147483648;
var_dump($large_number);
// вывод: float(2147483648)

// это справедливо и для шестнадцатеричных целых:
var_dump0x80000000 );
// вывод: float(2147483648)

$million 1000000;
$large_number =  50000 $million;
var_dump($large_number);
// вывод: float(50000000000)
?>
Внимание

К сожалению, в PHP была ошибка, так что это не всегда верно работает, когда используются отрицательные числа. Например: когда вы умножаете -50000 * $million, результатом будет -429496728. Однако, если оба операнда положительны, проблем не возникает.

Эта ошибка устранена в PHP 4.1.0.

в PHP не существует оператора деления целых. Результатом 1/2 будет число с плавающей точкой 0.5. Вы можете привести значение к целому, что всегда округляет его в меньшую сторону, либо использовать функцию round().

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

Преобразование в целое

Для несомненного преобразования значения в целое используйте приведение типа (int) или (integer). Однако в большинстве случаев вам нет необходимости использовать приведение типа, поскольку значение будет автоматически преобразовано, если оператор, функция или управляющая конструкция требует целый аргумент. Вы также можете преобразовать значение в целое при помощи функции intval().

Смотрите также Манипуляции с типами.

Из булева типа

FALSE преобразуется в 0 (ноль), а TRUE - в 1 (единицу).

Из чисел с плавающей точкой

При преобразовании из числа с плавающей точкой в целое, число будет округлено в сторону нуля.

Если число с плавающей точкой превышает пределы целого (как правило, это +/- 2.15e+9 = 2^31), результат будет неопределенным, так как целое не имеет достаточной точности, чтобы вернуть верный результат. В этом случае не будет выведено ни предупреждения, ни даже замечания!

Внимание

Никогда не приводите неизвестную дробь к целому, так как это может иногда дать неожиданные результаты.

<?php
echo (int) ( (0.1+0.7) * 10 ); // выводит 7!
?>
Смотрите более подробно: предупреждение о точности чисел с плавающей точкой.

Из других типов

Предостережение

Для других типов поведение преобразования в целое не определено. В настоящее время поведение такое же, как если бы значение сперва было преобразовано в булев тип. Однако не полагайтесь на это поведение, так как он может измениться без предупреждения.

Коментарии

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
2006-12-12 15:42:45
http://php5.kiev.ua/manual/ru/language.types.integer.html
Автор:
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'
2007-03-09 09:26:37
http://php5.kiev.ua/manual/ru/language.types.integer.html
Автор:
On 64 bits machines max integer value is 0x7fffffffffffffff (9 223 372 036 854 775 807).
2007-03-10 06:51:36
http://php5.kiev.ua/manual/ru/language.types.integer.html
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(=>
                   
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);
?>
2007-08-13 08:33:19
http://php5.kiev.ua/manual/ru/language.types.integer.html
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
2013-02-28 20:25:57
http://php5.kiev.ua/manual/ru/language.types.integer.html
Автор:
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
2015-01-09 11:31:09
http://php5.kiev.ua/manual/ru/language.types.integer.html
Автор:
<?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.
2016-02-25 10:26:28
http://php5.kiev.ua/manual/ru/language.types.integer.html
Автор:
-------------------------------------------------------------------------
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
2017-11-20 18:04:49
http://php5.kiev.ua/manual/ru/language.types.integer.html
"There is no integer division operator in PHP". But since PHP 7, there is the intdiv function.
2017-11-27 12:01:06
http://php5.kiev.ua/manual/ru/language.types.integer.html
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 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 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).
2020-08-07 10:34:02
http://php5.kiev.ua/manual/ru/language.types.integer.html
Regarding the part about `PHP does not support unsigned ints`, this often causes much confusion when using the hard-coded minimum value of a signed integer that matches PHP_INT_MIN.

<?php
// 64-bit example
var_dump(PHP_INT_MIN);
var_dump(-9223372036854775808);
var_dump(PHP_INT_MIN === -9223372036854775808);
// int(-9223372036854775808)
// float(-9.223372036854776E+18)
// bool(false)
?>

Although visually, I've typed the same value that PHP_INT_MIN writes out `-9223372036854775808`, the language parser only understands it as two expressions with a negate operator followed by `9223372036854775808`. The value exceeds the maximum value of an integer by one, and is promoted to a float. Although it's been suggested in the past to wire up a hook to look for this value specifically, it's more difficult than it sounds. The tokenizer is unable to evaluate both the negate and integer as one token. In addition, you would also need to address binary, octal, and hex literals.

<?php
var_dump
(-9223372036854775808); // literal decimal
var_dump(-0x8000000000000000); // literal hex
var_dump(-0b1000000000000000000000000000000000000000000000000000000000000000); // literal binary
var_dump(-01000000000000000000000); // literal octal
?>

If you need to hard-code the minimum value, use `PHP_INT_MIN`. It was introduced specifically for this edge case. Alternative methods are to write `-9223372036854775807 - 1`.
2024-06-18 11:59:16
http://php5.kiev.ua/manual/ru/language.types.integer.html

    Поддержать сайт на родительском проекте КГБ