PHP | intdiv () Функция

Опубликовано: 24 Февраля, 2022

intdiv означает целочисленное деление. Эта функция возвращает целое частное от деления данного делимого и делителя. Эта функция внутренне удаляет остаток от делимого, чтобы он делился без остатка на делитель, и возвращает частное после деления.

Синтаксис:

int intdiv ($ дивиденд, $ делитель)

Параметры : функция принимает два следующих параметра:

  • $ Divivend: этот целочисленный параметр со знаком относится к числу, которое нужно разделить.
  • $ divisor: этот целочисленный параметр со знаком относится к числу, которое будет использоваться в качестве делителя.

Тип возвращаемого значения: эта функция возвращает вычисленное частное.

Примеры:

Input :  $dividend = 5, $divisor = 2
Output : 2

Input : $dividend = -11, $divisor = 2
Output : -5        

Exception/Error:: The function raises exception in following cases:

  • If we pass the divisor as 0, then the function raises DivisionByZeroError exception.
  • If we pass PHP_INT_MIN as the dividend and -1 as the divisor, then an ArithmeticError exception is thrown.

    Below program illustrates the working of intdiv in PHP:

    <?php
      
    // PHP code to illustrate the working 
    // of intdiv() Functions 
      
    $dividend = 19;
    $divisor = 3; 
      
    echo intdiv($dividend, $divisor);
      
    ?>

    Output:

    6
    

    After Seeing so far many may think that this function is equivalent to

    floor($dividend/$divisor)

    but the example will elaborate the difference.

    <?php
      
    // PHP code to differentiate between 
    // intdiv() and floor() 
      
    $dividend = -19;
    $divisor = 3; 
      
    echo intdiv($dividend, $divisor) ." "
                 floor($dividend/ $divisor);
      
    ?>

    Output:

    -6
    -7
    

    Important points to note:

    • intdiv() Function returns the quotient of integer division.
    • The function may raise exceptions thus the developer has to tackle edge cases.
    • The function is not equivalent to the floor function applied to the float division or ‘/’.

    Reference:
    http://php.net/manual/en/function.intdiv.php

PHP