Lets say I have an array of numbers: [1,2,3]
.
How can I loop through this array
to create an array of possible permutations.
I'm expecting outputs like:
[1,2]
, [1,3]
, [2,1]
, [2,3]
, [3,1]
, [3,2]
.
Lets say I have an array of numbers: [1,2,3]
.
How can I loop through this array
to create an array of possible permutations.
I'm expecting outputs like:
[1,2]
, [1,3]
, [2,1]
, [2,3]
, [3,1]
, [3,2]
.
Do the following:
$input = array(1,2,3);
$output = array();
// to get all possible permutations
// for first value in the permutation, loop over all array values
foreach ($input as $value1) {
// for second value in the permutation, loop again similarly
foreach ($input as $value2) {
if ($value1 !== $value2) // dont consider same values
$output[] = array($value1, $value2);
}
}