Generating Permutations of an Array in PHP
In PHP, generating permutations of an array involves arranging all of its elements in every possible order. For instance, given an array of strings ['peter', 'paul', 'mary'], we aim to generate the following permutations:
peter-paul-mary
peter-mary-paul
paul-peter-mary
paul-mary-peter
mary-peter-paul
mary-paul-peter
To address this problem, we present two PHP functions.
Function 1:
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);
Function 2:
function pc_next_permutation($p, $size) { for ($i = $size - 1; $p[$i] >= $p[$i+1]; --$i) { } if ($i == -1) { return false; } for ($j = $size; $p[$j] <= $p[$i]; --$j) { } $tmp = $p[$i]; $p[$i] = $p[$j]; $p[$j] = $tmp; 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'); $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"; }
These functions provide two different approaches to generate permutations in PHP, allowing you to select the one that best suits your needs.
The above is the detailed content of How to Generate all Permutations of an Array in PHP?. For more information, please follow other related articles on the PHP Chinese website!