CodesCompiler
🔍
HTMLCSSJavaScriptPythonSQLPHPSEOPostsBooksKids About Contact 🚀 Get Started Free

PHP - Integer Division

PHP Integer Division

PHP has introduced a new function intdiv(), which performs integer division of its operands and return the division as int.

The intdiv() function returns integer quotient of two integer parameters. If “a/b” results in “c” as division and “r” as remainder such that −

PHP CODE
a=b*c+r

In this case,intdiv(a,b)returnsr−

PHP CODE
intdiv ( int $x , int $y ) : int

The $x and $y are the numerator and denominator parts of the division expression. The intdiv() function returns an integer. The return value is positive if both parameters are positive or both parameters are negative.

Example 1

If numerator is < denominator, the intdiv() function returns “0”, as shown below −

PHP CODE
&lt;?php
   $x=10;
   $y=3; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
   $r=intdiv($y, $x);
   echo "intdiv(" . $y . "," . $x . ") = " . $r;
?&gt;

It will produce the followingoutput−

PHP CODE
intdiv(10,3) = 3
intdiv(3,10) = 0

Example 2

In the following example, the intdiv() function returns negative integer because either the numerator or denominator is negative.

PHP CODE
&lt;?php
   $x=10;
   $y=-3; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
   $x=-10;
   $y=3; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
?&gt;

It will produce the followingoutput−

PHP CODE
intdiv(10,-3) = -3
intdiv(-10,3) = -3

Example 3

The intdiv() function returns a positive integer in the case of numerator and denominator both being positive or both being negative.

PHP CODE
&lt;?php
   $x=10;
   $y=3; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";

   $x=-10;
   $y=-3; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r ;
?&gt;

It will produce the followingoutput−

PHP CODE
intdiv(10,3) = 3
intdiv(-10,-3) = 3

Example 4

In the following example, the denominator is “0”. It results inDivisionByZeroErrorexception.

PHP CODE
&lt;?php
   $x=10;
   $y=0; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
?&gt;

It will produce the followingoutput−

PHP CODE
PHP Fatal error:  Uncaught DivisionByZeroError: Division by zero in hello.php:4