I edited your function to always reach 100%, at least 1% for each value (but the latter values are often very low, and the trend increases with the number of percent to generate):
function randomPercentages($x) {
$percent = 100;
$return = array();
for($i=1; $i <= $x; $i++) {
if($i < $x) {
$temp = mt_rand(1, ($percent-($x-$i)));
} else {
$temp = $percent;
}
$return[] = $temp;
$percent -= $temp;
}
return $return;
}
And here is a rewritten and tested function with a great idea and code from Felk (but zero values are possible):
function randomPercentagesFelk($x) {
$temp[] = 0;
for($i=1; $i<$x; $i++) {
$temp[] = mt_rand(1, 99);
}
$temp[] = 100;
sort($temp);
$percentages = [];
for($i=1; $i<count($temp); $i++) {
$percentages[] = $temp[$i] - $temp[$i-1];
}
return $percentages;
}
" 0" ( 98 - , ). , : 98 0,01-0,04 :
function randomPercentagesFelkZero($x) {
$temp[] = 0;
for($i=1; $i<$x; $i++) {
$new = mt_rand(1, 99);
if($i<98) {
while(in_array($new,$temp)) {
$new = mt_rand(1, 99);
}
}
$temp[] = $new;
}
$temp[] = 100;
sort($temp);
$percentages = [];
for($i=1; $i<count($temp); $i++) {
$percentages[] = $temp[$i] - $temp[$i-1];
}
return $percentages;
}