Starting with PHP 7.0, you can use the intdiv()
function to perform integer division, which returns the result of the division as an integer, discarding any remainder. It takes the following two arguments:
- The dividend (the number being divided), and;
- The divisor (the number by which the dividend is being divided);
For example, you can use it like this:
// PHP 7+ var_dump(intdiv(10, 3)); // 3 var_dump(intdiv(-10, 3)); // -3 var_dump(intdiv(10, -3)); // -3
// PHP 7+ var_dump(intdiv(5, 2)); // 2 var_dump(intdiv(-5, 2)); // -2 var_dump(intdiv(5, -2)); // -2
// PHP 7+ var_dump(intdiv(10, 1)); // 10 var_dump(intdiv(-10, 1)); // -10 var_dump(intdiv(10, -1)); // -10
As an alternative, you may also perform regular division and then get the integer part of the resulting decimal number. For example, one way to do so would be to simply cast the result to integer, like so:
var_dump((int) (10 / 3)); // 3 var_dump((int) (-10 / 3)); // -3 var_dump((int) (10 / -3)); // -3 var_dump((int) 3.333); // 3 var_dump((int) -3.333); // -3
var_dump((int) (5 / 2)); // 2 var_dump((int) (-5 / 2)); // -2 var_dump((int) (5 / -2)); // -2 var_dump((int) 2.5); // 2 var_dump((int) -2.5); // -2
var_dump((int) (10 / 1)); // 10 var_dump((int) (-10 / 1)); // -10 var_dump((int) (10 / -1)); // -10 var_dump((int) 10.0); // 10 var_dump((int) -10.0); // -10
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.