Divide an integer evenly into X parts

I am looking for an efficient way in PHP to split a number in equal parts. The number will always be an integer (without a float).

Let's say that I have an array of $ hours with values ​​from "1" to "24" ($ hours ['1'], etc.) and a variable $ int containing an integer. What I want to achieve evenly distributes the value of $ int in 24 parts, so I can evaluate the value for each corresponding array entry. (If the number is odd, the rest will be added to the last or first values ​​in 24).

Hi,

+3
source share
2 answers

Here is the algorithm you are looking for; it evenly distributes an integer Nover the Kcells:

for i = 0 to K
    array[i] = N / K    # integer division

# divide up the remainder
for i = 0 to N mod K
    array[i] += 1
+14

<?php
$num = 400;
$val = floor($num/24);

for($i=0;$i<24;$i++) {
    $arr[$i] = $val;
}

$arr[0] += $num - array_sum($arr);
?>
+3

All Articles