Although the PHP language is powerful, it does not mean that it has no shortcomings. In the process of writing code, you will inevitably encounter some headaches. Below we will introduce to you the solution to the PHP integer remainder return negative number.
Let’s look at an example first.
In fact, this can be considered a BUG in PHP. The most important thing is that PHP is a weakly typed language. It has a built-in machine to determine the user type.
But a machine is a machine after all. There are times when judgments are wrong. Just like the above. So at this time we need manual intervention.
So I thought of using the following method to solve the problem of PHP integer remainder returning a negative number.
We see that the result is still wrong - 5069794.
But it is worth noting that the return is an int type.
Think about it in detail. The problem of PHP integer remainder returning a negative number is handled like this.
PHP remainder is an integer by default.
And when you define $res = 16244799483;
In fact, it has already overflowed. So we need to add forced type conversion. It becomes a float type.
But this is not enough. Because the modulo calculation of % is still based on integers.
So we need a function fmod. It is for float type.
So the final solution to PHP integer remainder returning a negative number is:
In this way we solve the problem of PHP integer remainder returning a negative number.:)