3v4l.org

run code in 300+ PHP versions simultaneously
<?php function getRandWithStipulations(int $total, int $count, array $scope): array { if ($scope[0] > $scope[1]) { throw new Exception('Argument 3 (\$scope) is expected to contain a minimum integer then a maximum integer.'); } if ($scope[1] * $count < $total) { throw new Exception('Arguments 2 (\$count) and 3 (\$scope) cannot satisfy argument 1 (\$total).'); } $result = []; for ($x = 1; $x < $count; ++$x) { // count - 1 iterations $scope[0] = max($scope[0], $total - ($scope[1] * ($count - $x))); $scope[1] = min($scope[1], $total - ($scope[0] * ($count - $x))); $rand = rand(...$scope); $result[] = $rand; $total -= $rand; } $result[] = $total; return $result; } var_export(getRandWithStipulations(130, 3, [23, 70]));

preferences:
26.83 ms | 407 KiB | 5 Q