Humaira Naaz Humaira Naaz - 7 months ago 85
PHP Question

PHP 7 intdiv() vx floor or custom type cast

I am looking PHP 7 new Additions in order to improve my skills, i want to know what exactly the difference between the

or custom
type cast

for example

echo (int) (8/3); // 2
echo floor((8/3)); // 2
echo intdiv((8/3)); // 2

what exactly the reason for this function to add in newer version of PHP.

Answer Source

In general all these three you mentioned works similar as of your example but intdiv() will give you more accurate result while working extremely large set of numbers

here is example you can see.

echo PHP_INT_MAX; // 9223372036854775807

echo (int)(PHP_INT_MAX/2); // 4611686018427387904
// here you can look the ending number

echo floor(PHP_INT_MAX/2); // 4.6116860184274E+18
// here you can see floor will return scientific notation for larger numbers

echo intdiv(PHP_INT_MAX,2); // 4611686018427387903
// you can compare the result return by (int) cast

intdiv() always give you positive number or in other word intdiv() let you know how many times you can divide evenly

Another example developer always use Modulus Operator in order to get remainder but intdiv() will always return you positive numbers and let you know how many times you can divide evenly.

echo (5 % 2) // 1
echo intdiv(5, 2) // 2

Hope this good enough to understand the difference among all 3 of them..

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download