Relevant Solutions for PHP Integer Return Negative

  • 2021-06-28 11:25:50
  • OfStack

The PHP language is powerful, but it doesn't mean it has no drawbacks. There are some headaches in writing code.Below we will introduce the solution of returning negative numbers from the balance of PHP integers.

Let's start with an example.


$res = 16244799483; 
echo $res%9999999; 
//  The output is  -5069794 ,   The correct result should be 4801107

Actually, this is PHP 1 BUG. Essentially, PHP is a weakly typed language. It has a built-in machine to determine the type of user.

But after all, machines are machines. There are also times when judgments go wrong, just like above. So at this point we need manual intervention.

So I thought I would use the following method to solve the problem of PHP integer balance returning negative numbers.


$res = floatval(16244799483); 
var_dump($res % 9999999);

We see that the result is still wrong - 5069794.

However, it is worth noting that the return is of type int.

Think about it in detail. This is how the PHP integer balance returns negative numbers.

The PHP balance defaults to integer.

And when you define $res = 16244799483;

Actually it's already overflowed. So add a cast. Turn into float type.

But that's not enough. Because% is still an integer.

So we need a function fmod. It's for the float type.

So the final solution for PHP integer balance returning negative numbers is:


$res = floatval(16244799483); 
var_dump(fmod($res,9999999));

This solves the problem of returning negative numbers from PHP integer remainder:)


Related articles: