Permute an array of values.
<?php
$arr = array(1,2,3,4,5);
$perms = new permutation($arr);
print_r($perms->results);
?>
OUTPUT:
Array
(
[0] => 12345
[1] => 12354
[2] => 12435
[3] => 12453
[4] => 12534
[5] => 12543
[6] => 13245
[7] => 13254
[8] => 13425
[9] => 13452
[10] => 13524
[11] => 13542
[12] => 14235
[13] => 14253
[14] => 14325
[15] => 14352
[16] => 14523
[17] => 14532
[18] => 15234
[19] => 15243
[20] => 15324
[21] => 15342
[22] => 15423
[23] => 15432
[24] => 21345
[25] => 21354
[26] => 21435
[27] => 21453
[28] => 21534
[29] => 21543
[30] => 23145
[31] => 23154
[32] => 23415
[33] => 23451
[34] => 23514
[35] => 23541
[36] => 24135
[37] => 24153
[38] => 24315
[39] => 24351
[40] => 24513
[41] => 24531
[42] => 25134
[43] => 25143
[44] => 25314
[45] => 25341
[46] => 25413
[47] => 25431
[48] => 31245
[49] => 31254
[50] => 31425
[51] => 31452
[52] => 31524
[53] => 31542
[54] => 32145
[55] => 32154
[56] => 32415
[57] => 32451
[58] => 32514
[59] => 32541
[60] => 34125
[61] => 34152
[62] => 34215
[63] => 34251
[64] => 34512
[65] => 34521
[66] => 35124
[67] => 35142
[68] => 35214
[69] => 35241
[70] => 35412
[71] => 35421
[72] => 41235
[73] => 41253
[74] => 41325
[75] => 41352
[76] => 41523
[77] => 41532
[78] => 42135
[79] => 42153
[80] => 42315
[81] => 42351
[82] => 42513
[83] => 42531
[84] => 43125
[85] => 43152
[86] => 43215
[87] => 43251
[88] => 43512
[89] => 43521
[90] => 45123
[91] => 45132
[92] => 45213
[93] => 45231
[94] => 45312
[95] => 45321
[96] => 51234
[97] => 51243
[98] => 51324
[99] => 51342
[100] => 51423
[101] => 51432
[102] => 52134
[103] => 52143
[104] => 52314
[105] => 52341
[106] => 52413
[107] => 52431
[108] => 53124
[109] => 53142
[110] => 53214
[111] => 53241
[112] => 53412
[113] => 53421
[114] => 54123
[115] => 54132
[116] => 54213
[117] => 54231
[118] => 54312
[119] => 54321
)
The nature of the input allows you to pass either a string or an int into the function as a singular value:
<?php
$arr = array('you','are','not','very','cool');
$arr = array('you','are','#',1);
?>
I'd advise staying under 9 values, as the amount of permutations required is
aᵢ=i!
You can see a list of amounts here: http://www4d.wolframalpha.com/Calculate/MSP/MSP11619hfc32hdb0fb84f00002gb116g73ib5b7g0?MSPStoreType=image/gif&s=31&w=350&h=1008
class permutation {
public $permutations = array();
function __construct(array $arr) { $this->showPerms($this->permute($arr)); }
private function showPerms($a,$i='') {
if (is_array($a))
foreach($a as $k => $v)
$this->showPerms($v,$i.$k);
else
$this->results[] = $i.$a;
}
private function permute(array $arr) {
$out = array();
if (count($arr) > 1)
foreach($arr as $r => $c) {
$n = $arr;
unset($n[$r]);
$out[$c] = $this->permute($n);
}
else
return array_shift($arr);
return $out;
}
}