How can I find all possible combinations from a given 3 digit number using PHP?
for example if the number is 123
, the possible array results should be following
123,132,213,321,321,312
and when a number repeats, there should be no duplicates. example
$threedigit="001";
result should be
001,010,100
there is more possible numbers.
How I achieve this using PHP ?
This would be an example of a simple solution for a fixed length of 3 digits:
<?php
function permutations($input) {
$digit = str_split($input, 1);
$output = [];
for ($i=0; $i<3; $i++) {
for ($j=0; $j<3; $j++) {
if ($i==$j) continue;
for ($k=0; $k<3; $k++) {
if ($i==$k || $j==$k) continue;
$output[] = $digit[$i] . $digit[$j] . $digit[$k];
}
}
}
return array_unique($output);
}
print_r(permutations("123"));
print_r(permutations("001"));
The obvious output contains first 6, second 3 entries:
Array
(
[0] => 123
[1] => 132
[2] => 213
[3] => 231
[4] => 312
[5] => 321
)
Array
(
[0] => 001
[1] => 010
[4] => 100
)