3v4l.org

run code in 300+ PHP versions simultaneously
<?php function permStacker($array,$length){ $stack=[[]]; // declare intitial empty element for($x=0; $x<$length; ++$x){ // limit the total number of passes / max string length foreach($stack as $combination){ foreach(array_diff($array,range('a',end($combination))) as $left){ // do not include iterate letter that come earlier than rightmost letter $merge=array_merge($combination,[$left]); $stack[implode($merge)]=$merge; // keys hold desired strings, values hold subarray of combinations for iterated referencing } } } unset($stack[0]); // remove initial empty element return array_keys($stack); // return array of permutations as space delimited strings } $permutations=permStacker(range('a','h'),4); echo 'Total Permutations: ',sizeof($permutations),"\n"; var_export($permutations);

preferences:
27.73 ms | 410 KiB | 5 Q