Reputation: 122
I got an issue in Integer dividing script. What I want is, If we divide 8 into 3 parts. It should show all rounded figures. like, 3,3,2 If we SUM these 3. it will be 8.
But The Following script is dividing with some difference. It divides 2,2,4. It is also 8. But I like the above 1. Can any one help in this case please. Here is the code.
$numbertodivise = 8;
$no = 3;
$intnumber = intval($numbertodivise / $no);
$rem = $numbertodivise % $no;
$array = [];
for($i=1;$i<=$no;$i++) {
if($i==$no) {
$array[] = $intnumber + $rem;
} else {
$array[] = $intnumber;
}
}
print_r($array);
its out put is
Array ( [0] => 2 [1] => 2 [2] => 4 )
Kindly Help me to make it like this
Array ( [0] => 3 [1] => 3 [2] => 2 )
8 is not a fixed integer. It will by dynamic.. 8,9,19,22, 88, 9888, any digit it could be.
Upvotes: 0
Views: 60
Reputation: 311
Edit changed the$turn
to $no
in for loop.
You can use this for any number.
<?php
$numbertodivide = 8;
$no = 3;
$array = [];
$added=0;//initialize the variable to track added number to make the given number divisible
while($numbertodivide%$no){
$numbertodivide+=1;
$added++;
}
$turn=$numbertodivide/$no;//get how many times we have to repeat the divider to get the given number
for($i=0;$i<$no-1;$i++){
$array[]=$turn;
}
$array[]=$turn-$added;//trim the added number from the last input of the number.
?>
Upvotes: 1
Reputation: 781592
intval()
rounds down. You want to round up, so use ceil()
.
$intnumber = ceil($numbertodivise / $no);
$rem = $numbertodivise % $intnumber;
$array = array_fill(0, $no, $intnumber);
if ($rem != 0) {
$array[count($array)-1] = $rem;
}
Upvotes: 0
Reputation: 3385
Without the need of loops. Using your variables:
$count = ceil($numbertodivise / $no);
$rem = $numbertodivise - ($no * ($count-1));
$array = array_fill(0,$count-1,$no);
$array[] = $rem;
Result:
Array
(
[0] => 3
[1] => 3
[2] => 2
)
Upvotes: 0