$sortFunc = function($val) { $strArr = str_split($val); sort($strArr); return implode("", $strArr); }; $arr = array("cat", "dog", "tac", "god", "act"); $words = array(); $index = array(); // form a new array with each string sorted within itself $words = array_map($sortFunc, $arr); // form a index array in order to remember original index foreach ($words as $key => $val) { $index[$key] = $val; } asort($index); // sort the values but maintain index association foreach ($index as $key => $val) { // use index value in the original array to print echo $arr[$key] . "\n"; }
http://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together/