Hướng dẫn php divide without decimal

The thing i want to do is :

   $numbertodivise = 500;

   500 / 3 = 166,66

I want to divise the number in the most equitable part and the last part to add the difference , exemple :

  500 / 3 will give me :
  $result1 = 166
  $result2 = 166
  $result3 = 168

i want the code for every division how is the best way to do that ?

asked Dec 15, 2017 at 12:26

2

Here I have extracted the remainder of the numbertodivise e.g. 2 if modulus with 3, and later I divided and extracted the integer part of the division so that I can add the remainder into last divided number i.e. 166 in this case.

";
print_r($array);
?>

Output will look like this:

Array
(
    [0] => 166
    [1] => 166
    [2] => 168
)

For making variables as you mentioned use:


Jay Blanchard

33.6k16 gold badges73 silver badges113 bronze badges

answered Dec 15, 2017 at 12:36

Hướng dẫn php divide without decimal

pravindot17pravindot17

1,1651 gold badge15 silver badges31 bronze badges

2

For PHP 7, you can use this function (check comment for <7):

function get_results($val, $qt){
    $division = intdiv($val, $qt); // PHP <7: $division = ($val - ($val % $qt)) / $qt;
    $ret = array_fill(0, $qt, $division); // fill array with $qt equal values
    if($division != $val / $qt){ // if not whole division, add remaning to lsat element
        $ret[count($ret)-1] = $ret[0] + ($val % $qt);
    }return $ret;
}

Use it like this:

print_r(get_results(500, 3));

And the output will be:

Array
(
    [0] => 166
    [1] => 166
    [2] => 168
)

answered Dec 15, 2017 at 12:37

Hướng dẫn php divide without decimal

FirstOneFirstOne

5,6415 gold badges25 silver badges45 bronze badges

A method that does not loop and uses basic PHP functions.

I use array_fill to fill the array with the floor of the calculation.
Then I add the remainder to the last item in the array.

$number = 500;
$divise =3;

$arr = array_fill(0, $divise, floor($number/$divise));
$arr[count($arr)-1] += $number-(floor($number/$divise)*$divise);
// Above line can also be . $arr[count($arr)-1] += $number-$arr[0]*$divise;
Var_dump($arr);

https://3v4l.org/hFrDc

answered Dec 15, 2017 at 13:18

Hướng dẫn php divide without decimal

AndreasAndreas

23.4k5 gold badges29 silver badges62 bronze badges

This is a way to do it using intval() and the modulo operator %:

';
        else
            // ($divide % $divideWidth) will return the remainder of
            // division between $divide and $divideWidth. 
            // The remainder is always an int value.
            echo (int($divide/$divideWith) + ($divide % $divideWith)).'
'; } ?>

The result of which will be:

This is result1: 166
This is result2: 166
This is result3: 168

answered Dec 15, 2017 at 13:05

Ivan86Ivan86

5,6372 gold badges13 silver badges30 bronze badges

5