This should work for you and even without evil()
.
So what does this code do?
1. How many permutations are there?
Pretty simple:
nl = amount of permutations
Where n
is the amount of words and l
the desired length of each combination.
So for this specific example there are 3 words (apple
, patatoes
and orange
) and we want each permutation with a length of 3. Means:
33 = 27 permutations
2. Getting all permutations together
We loop through all our permutations, which we already have(Starting off with one permutation, an "empty permutation" ($permutations = [[]];
)), and for each permutation we go through our data array and combine each permutation with each input data to a new permutation.
Now we do this until we get the desired length for each permutation.
2.1 Example
Input data:
[1, 2] //Input array with the data
length = 2 //Desired length for each permutation
//↓ new permutations for the next iteration
│
iteration 0:
Permutations:
- [] │ -> []
│
iteration 1: ┌─────────────┤
│ │
Permutations: v v
- [] + 1 │ -> [1]
- [] + 2 │ -> [2]
│
iteration 2: ┌─────────────┤
│ │
Permutations: v v
- [] + 1 │ -> [1]
- [] + 2 │ -> [2]
- [1] + 1 │ -> [1,1] //desired length 2
- [1] + 2 │ -> [1,2] //desired length 2
- [2] + 1 │ -> [2,1] //desired length 2
- [2] + 2 │ -> [2,2] //desired length 2
//↑ All permutations here
So as you can see in the above example we now have all permutations with the desired length which we want, here 2.
But to get only the permutations with the desired length we are overwriting the result array each iteration, so that at the end only the permutations with the expected length are in the results array.
3. Code:
<?php
function getPermutations($input = [], $length = 2, $delimiter = ",") {
$permutations = [[]];
$data = is_array($input) ? $input : explode($delimiter, $input);
for ($count = 0; $count < $length; $count++) {
$tmp = [];
foreach ($permutations as $permutation) {
foreach ($data as $inputValue)
$tmp[] = array_merge($permutation, [$inputValue]);
}
$permutations = $tmp;
}
return $permutations;
}
$result = getPermutations("apple,patatoes,orange", 3);
print_r($result);
?>
output:
Array
(
[0] => Array
(
[0] => apple
[1] => apple
[2] => apple
)
//...
[26] => Array
(
[0] => orange
[1] => orange
[2] => orange
)
)