- What’s the Maximum Value For an Int in PHP
- PHP Largest Possible Integer Constant
- purpose of the max number in php & mysql
- INT max size for 32bit system
- What is the maximum value for an int32?
- How to get max() of integer value from a varchar field in codeigniter?
- Php максимальное значение int
- Переполнение целых чисел
- Преобразование в целое
- Из булевого типа
- Из чисел с плавающей точкой
- Из строк
- Из NULL
- Из других типов
- User Contributed Notes 19 notes
- PHP Numbers
- PHP Numbers
- PHP Integers
- Example
What’s the Maximum Value For an Int in PHP
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 using the constant
PHP_INT_SIZE, and maximum value using
the constant PHP_INT_MAX since PHP
4.4.0 and PHP 5.0.5.64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit.
PHP Largest Possible Integer Constant
PHP_INT_MAX (integer)
Available since PHP 4.4.0 and PHP 5.0.5
purpose of the max number in php & mysql
It’s hardware limit of the CPU. You can still use bc math function to work with larger numbers. In mysql it is about aligning bytes, so it knows at which offset is which column.
The multiply result is converted to float.
INT max size for 32bit system
You are using the whole 32 bits. It’s just that the default output functions interpret it as signed integer. If you want to display the value «raw» use:
printf("%u", -1); // %u for unsigned
Since PHP handles the integers signed internally however, you can only use bit arithmetics, but not addition/multiplication etc. with them — if you expect them to behave like unsigned ints.
What is the maximum value for an int32?
It’s 2,147,483,647. Easiest way to memorize it is via a tattoo.
How to get max() of integer value from a varchar field in codeigniter?
First, make sure column rf_name data type should be integer/float, not varchar/string/text etc.
So, according to the data type of the column, it will not store any string value
$maxid = $this->db->query('SELECT MAX(rf_name) AS maxid FROM table')->row()->maxid;
$this->db->select_max('rf_name');
$query = $this->db->get('table');
If you have both string and numeric values you have to do the following steps
$this->db->select('rf_name');
$this-db->from('table');
$values = $this->db->get('table')->result_array();
$only_values= array();
foreach($values as $value) if (is_numeric($value['rf_name'])) array_push($only_values, $value['rf_name']);
>
>
$max_value = max($only_values);
Php максимальное значение int
Целые числа ( int ) могут быть указаны в десятичной (основание 10), шестнадцатеричной (основание 16), восьмеричной (основание 8) или двоичной (основание 2) системе счисления. Для задания отрицательных целых ( int ) используется оператор отрицания
Для записи в восьмеричной системе счисления, необходимо поставить перед числом 0 (ноль). Начиная с PHP 8.1.0, восьмеричной нотации также может предшествовать 0o или 0O . Для записи в шестнадцатеричной системе счисления, необходимо поставить перед числом 0x . Для записи в двоичной системе счисления, необходимо поставить перед числом 0b
Начиная с PHP 7.4.0, целочисленные литералы могут содержать подчёркивания ( _ ) между цифрами для лучшей читаемости литералов. Эти подчёркивания удаляются сканером PHP.
Пример #1 Целые числа
$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)
?>?php
Формально, структура целых чисел int принята в PHP 8.1.0 (ранее не допускались восьмеричные префиксы 0o или 0O , а до PHP 7.4.0 не допускалось подчёркивание):
десятичные : 81*(_5+)* | 0 шестнадцатеричные : 0[xX][0-9a-fA-F]+(_[0-9a-fA-F]+)* восьмеричные : 0[oO]?2+(_1+)* двоичные : 0[bB][01]+(_[01]+)* целые : десятичные | шестнадцатеричные | восьмеричные | двоичные
Размер типа int зависит от платформы, хотя, как правило, максимальное значение примерно равно 2 миллиардам (это 32-битное знаковое). 64-битные платформы обычно имеют максимальное значение около 9E18. PHP не поддерживает беззнаковые целые числа ( int ). Размер int может быть определён с помощью константы PHP_INT_SIZE , максимальное значение — с помощью константы PHP_INT_MAX , а с помощью константы PHP_INT_MIN можно определить минимальное значение.
Переполнение целых чисел
Если PHP обнаружил, что число превышает размер типа int , он будет интерпретировать его в качестве float . Аналогично, если результат операции лежит за границами типа int , он будет преобразован в float .
Пример #2 Переполнение целых на 32-битных системах
$large_number = 2147483647 ;
var_dump ( $large_number ); // int(2147483647)
?php
$large_number = 2147483648 ;
var_dump ( $large_number ); // float(2147483648)
$million = 1000000 ;
$large_number = 50000 * $million ;
var_dump ( $large_number ); // float(50000000000)
?>
Пример #3 Переполнение целых на 64-битных системах
$large_number = 9223372036854775807 ;
var_dump ( $large_number ); // int(9223372036854775807)
?php
$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() .
var_dump ( 25 / 7 ); // float(3.5714285714286)
var_dump ((int) ( 25 / 7 )); // int(3)
var_dump ( round ( 25 / 7 )); // float(4)
?>?php
Преобразование в целое
Для явного преобразования в int , используйте приведение (int) или (integer) . Однако, в большинстве случаев, в приведении типа нет необходимости, так как значение будет автоматически преобразовано, если оператор, функция или управляющая структура требует аргумент типа int . Значение также может быть преобразовано в int с помощью функции intval() .
Если resource преобразуется в int , то результатом будет уникальный номер ресурса, привязанный к resource во время исполнения PHP программы.
Из булевого типа
false преобразуется в 0 (ноль), а true — в 1 (единицу).
Из чисел с плавающей точкой
При преобразовании из float в int , число будет округлено в сторону нуля. Начиная с PHP 8.1.0, при неявном преобразовании неинтегрального числа с плавающей точкой ( float ) в целое число ( int ), которое теряет точность, выдаётся уведомление об устаревании.
function foo ( $value ): int return $value ;
>
var_dump ( foo ( 8.1 )); // «Deprecated: Implicit conversion from float 8.1 to int loses precision» начиная с PHP 8.1.0
var_dump ( foo ( 8.1 )); // 8 до PHP 8.1.0
var_dump ( foo ( 8.0 )); // 8 в обоих случаях
var_dump ((int) 8.1 ); // 8 в обоих случаях
var_dump ( intval ( 8.1 )); // 8 в обоих случаях
?>
Если число с плавающей точкой превышает размеры int (обычно +/- 2.15e+9 = 2^31 на 32-битных системах и +/- 9.22e+18 = 2^63 на 64-битных системах, результат будет неопределённым, так как float не имеет достаточной точности, чтобы вернуть верный результат в виде целого числа ( int ). В этом случае не будет выведено ни предупреждения, ни даже замечания!
Замечание:
Значения NaN и Infinity при приведении к int становятся равными нулю, вместо неопределённого значения в зависимости от платформы.
Никогда не приводите неизвестную дробь к int , так как это иногда может дать неожиданные результаты.
Из строк
Если строка содержит число или ведущую числовую последовательность, тогда она будет преобразована в соответствующее целое число, в противном случае она преобразуется в ноль ( 0 ).
Из NULL
Значение null всегда преобразуется в ноль ( 0 ).
Из других типов
Для других типов поведение преобразования в int не определено. Не полагайтесь на любое наблюдаемое поведение, так как оно может измениться без предупреждения.
User Contributed Notes 19 notes
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
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:
$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 ()’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.
$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 );
?>
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
PHP Numbers
In this chapter we will look in depth into Integers, Floats, and Number Strings.
PHP Numbers
One thing to notice about PHP is that it provides automatic data type conversion.
So, if you assign an integer value to a variable, the type of that variable will automatically be an integer. Then, if you assign a string to the same variable, the type will change to a string.
This automatic conversion can sometimes break your code.
PHP Integers
2, 256, -256, 10358, -179567 are all integers.
An integer is a number without any decimal part.
An integer data type is a non-decimal number between -2147483648 and 2147483647 in 32 bit systems, and between -9223372036854775808 and 9223372036854775807 in 64 bit systems. A value greater (or lower) than this, will be stored as float, because it exceeds the limit of an integer.
Note: Another important thing to know is that even if 4 * 2.5 is 10, the result is stored as float, because one of the operands is a float (2.5).
Here are some rules for integers:
- An integer must have at least one digit
- An integer must NOT have a decimal point
- An integer can be either positive or negative
- Integers can be specified in three formats: decimal (10-based), hexadecimal (16-based — prefixed with 0x) or octal (8-based — prefixed with 0)
PHP has the following predefined constants for integers:
- PHP_INT_MAX — The largest integer supported
- PHP_INT_MIN — The smallest integer supported
- PHP_INT_SIZE — The size of an integer in bytes
PHP has the following functions to check if the type of a variable is integer:
Example
Check if the type of a variable is integer: