How to Divide and Get the Integer Value in PHP?

Get result of division as integer in PHP

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:

  1. The dividend (the number being divided), and;
  2. 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

Hope you found this post useful. It was published . Please show your love and support by sharing this post.