How to check if integer addition will overflow in PHP

1 Answer

0 votes
function addingWillOverflow(int $x, int $y): bool {
    return (($x > 0) && ($y > PHP_INT_MAX - $x)) || (($x < 0) && ($y < PHP_INT_MIN - $x));
}

$x = 39839299;
$y = 1472783642;
echo addingWillOverflow($x, $y) ? "true" : "false", PHP_EOL;

$x = 9223372036854775807; // PHP_INT_MAX
$y = 1872783642;
echo addingWillOverflow($x, $y) ? "true" : "false", PHP_EOL;


/*
run:

false
true

*/

 



answered May 17, 2025 by avibootz

Related questions

1 answer 238 views
1 answer 275 views
1 answer 251 views
1 answer 260 views
1 answer 262 views
...