3v4l.org

run code in 500+ PHP versions simultaneously
<?php $arr = [6,4,9,3,8,2,1,5]; // Calculate the total of the array elements $sum = array_sum($arr); $len = count($arr); // Using integer division and modulo arithmetic calculate the average and remainder $avg = intdiv($sum,$len); $rem = $sum % $len; // Create a result array and fill with the average $result = array_fill(0,$len,$avg); // Spread the remainder over the first few elements. while($rem){$result[--$rem]++;} var_dump($result); ?>
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.34, 8.2.0 - 8.2.30, 8.3.0 - 8.3.30, 8.4.1 - 8.4.21, 8.5.0 - 8.5.6
array(8) { [0]=> int(5) [1]=> int(5) [2]=> int(5) [3]=> int(5) [4]=> int(5) [5]=> int(5) [6]=> int(4) [7]=> int(4) }

preferences:
65 ms | 1274 KiB | 4 Q