If I understand the question, you have a max percentage (in your case 5) and a certain number of keys (in this case 1...4). You want to populate these four keys with all possible values of all integer percentages, zero included, up to the max included, with repetitions allowed.
So in this case from 0 0 0 0 up to 5 5 5 5.
In this case, you can have at the most pow($MaxPercentage+1, $keyNumber)
values in your result. Given any number from 0 to this maximum number, its combination will be
function nthCombo($idx, $keyNumber, $top) {
$result = array_fill(0, $keyNumber, 0);
$pos = 0;
while ($idx) {
$result[$pos++] = $idx % $top;
$idx = floor($idx / $top);
}
return $result;
}
So if you want all the percentages, all together:
$maxPercentage = 5;
$keyNumber = 4;
$top = $maxPercentage + 1;
$combinations = pow($top, $keyNumber);
print $combinations . "
";
for ($i = 0; $i < $combinations; $i++) {
$allcombi[] = nthCombo($i, $keyNumber, $top);
}
This also allows you to work without the need of actually storing the result, you can process it one value at a time.
(The mapping to named keys is immediate using array_combine()
)
specific percentages or strings
If you have a given number of percentages but they aren't in any simple progression (for example 11%, 13%, 22%, 22.5%, 27%, 31%), or maybe they are strings like [ 'foo', 'bar', 'baz' ], you can still use the approach above. You just use a map:
$percs = [ 11%, 13%, 22%, 22.5%, 27%, 31% ];
Now when the algorithm gives you $combo = [ 0, 2, 1, 5 ] you translate every number, e.g. 2, into $percs[2], which is 22%:
$perc2 = array_map(
function($idx) use ($percs) {
return $percs[$idx];
},
$combo
);
and obtain $perc2 = [ 11%, 22%, 13%, 31% ].