• PHP Video Tutorials

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 −

a=b*c+r

In this case, intdiv(a,b) returns r

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
   $x=10;
   $y=3; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
   $r=intdiv($y, $x);
   echo "intdiv(" . $y . "," . $x . ") = " . $r;
?>

It will produce the following output

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
   $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";
?>

It will produce the following output

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
   $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 ;
?>

It will produce the following output

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

Example 4

In the following example, the denominator is "0". It results in DivisionByZeroError exception.

<?php
   $x=10;
   $y=0; 
   $r=intdiv($x, $y);
   echo "intdiv(" . $x . "," . $y . ") = " . $r . "\n";
?>

It will produce the following output

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