This section describes what an arithmetic overflow condition, how the PHP 5 engine handles integer and float value overflow, how to write a PHP code to detect overflow conditions.
What is overflow?
Overflow or arithmetic overflow is a condition that occurs when a calculation produces a result
that is greater in magnitude than what a given data type can store or represent.
When applying this definition to PHP integer data type, we can say that:
PHP integer value overflow is a condition when an integer operation produces an integer outside the signed
32-bit integer value range.
When applying this definition to PHP float data type, we can say that:
PHP float value overflow is a condition when a float operation produces a float value outside the 64-bit
floating point number value range.
According to the PHP manual, here is how the PHP 5 engine handles arithmetic overflow conditions:
When integer value overflow happens at the upper limit of the integer value range, the resulting integer value
will be automatically converted to float data type.
When integer value overflow happens at the lower limit of the integer value range, the resulting integer value
will be automatically converted to float data type.
When float value overflow happens at the upper limit of the exponent value range, the resulting float value
will be automatically converted to a special value called "infinite".
When float value overflow happens at the lower limit of the exponent value range, the resulting float value
will be automatically converted to 0. This is also called underflow.
Note that in all arithmetic overflow cases, PHP will not abend the operation and raise any runtime errors.
So if you are writing a PHP code dealing with numbers that close to integer or float value range limits,
you need to be very careful and write extra code to detect overflow conditions yourself.
To help us understand what are integer and float value range and how to detect arithmetic overflow conditions,
I wrote this tutorial sample PHP script: