Most programming languages have limitations on variable types. Exceeding these limits will cause running problems or errors, and PHP is no exception. In PHP, the range of integer variables is -2147483648 to 2147483647. When this range is exceeded, the problem of exceeding the integer range will occur.
There may be many reasons for exceeding the range of the integer type, such as:
In order to better understand the problem of PHP exceeding the integer range, we can illustrate it through the following example.
For example, let us try to calculate the sum of two integers so that the result is outside the range of the integer type.
$x = 2147483647;
$y = 2;
echo $x $y; // The output result is -2147483647
Due to $x and $y The added result exceeds the maximum value of 2147483647, so PHP treats it as a negative number and outputs the result as -2147483647.
You can also manually set the integer variable to a value greater than 2147483647 to reproduce the integer overflow problem.
$x = 2147483648;
echo $x; //The output result is -2147483648
Because 2147483648 is greater than the largest integer value 2147483647, PHP treats it as a negative number -2147483648.
When reading data from other systems or interfaces, you need to pay attention to the problem of inconsistent data types.
For example, let us get a numerical data from a json file.
{"number": 12345678901234567890}
$json = file_get_contents("/path/to/json/file.json");
$data = json_decode($json, true );
$number = $data["number"];
echo $number; //The output result is 12345678901234567890
Since the maximum integer value in PHP is 2147483647, and reading If the value in the json file is greater than this value, PHP will treat it as a float instead of an integer.
Regarding how to solve the problem that PHP exceeds the integer range, there are the following solutions:
For example:
$x = "12345678901234567890";
$y = "9876543210987654321";
$sum = gmp_add($x, $y );
echo gmp_strval($sum); // The output result is: 22222222112222222211
In PHP development, exceeding the range of integers is a problem that cannot be ignored. Special attention needs to be paid during code writing and code review to prevent such problems from occurring.
The above is the detailed content of php exceeds the shaping range. For more information, please follow other related articles on the PHP Chinese website!