Home >Backend Development >PHP Tutorial >How Can I Generate All Possible Permutations of a PHP Array?
Finding All Permutations of a PHP Array
Given an array of strings, such as ['peter', 'paul', 'mary'], this article demonstrates how to generate all possible permutations of the array elements. By programming with PHP, you can achieve this goal with various functions.
One approach is to use the pc_permute function, which employs a recursive algorithm to generate the permutations. The function takes the input array as an argument and an optional parameter for an array to store the permutations. It iterates through the input array, generating new permutations by moving elements to the front of the list and recursively calling itself with the updated array.
Here's a code snippet illustrating the pc_permute function in action:
function pc_permute($items, $perms = array()) { if (empty($items)) { echo join(' ', $perms) . "<br />"; } else { for ($i = count($items) - 1; $i >= 0; --$i) { $newitems = $items; $newperms = $perms; list($foo) = array_splice($newitems, $i, 1); array_unshift($newperms, $foo); pc_permute($newitems, $newperms); } } } $arr = array('peter', 'paul', 'mary'); pc_permute($arr);
Another approach is to use the pc_next_permutation function, which generates permutations using a slightly different algorithm. It compares adjacent elements in the array and swaps them if necessary to generate the next permutation in the sequence.
Here's a code snippet for the pc_next_permutation function:
function pc_next_permutation($p, $size) { // slide down the array looking for where we're smaller than the next guy for ($i = $size - 1; $p[$i] >= $p[$i+1]; --$i) { } // if this doesn't occur, we've finished our permutations // the array is reversed: (1, 2, 3, 4) => (4, 3, 2, 1) if ($i == -1) { return false; } // slide down the array looking for a bigger number than what we found before for ($j = $size; $p[$j] <= $p[$i]; --$j) { } // swap them $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; // now reverse the elements in between by swapping the ends for (++$i, $j = $size; $i < $j; ++$i, --$j) { $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; } return $p; } $set = split(' ', 'she sells seashells'); // like array('she', 'sells', 'seashells') $size = count($set) - 1; $perm = range(0, $size); $j = 0; do { foreach ($perm as $i) { $perms[$j][] = $set[$i]; } } while ($perm = pc_next_permutation($perm, $size) and ++$j); foreach ($perms as $p) { print join(' ', $p) . "\n"; }
The above is the detailed content of How Can I Generate All Possible Permutations of a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!