// Groups an array of strings into subarrays of anagrams
function groupAnagrams(array $words): array {
$map = [];
foreach ($words as $word) {
if (!is_string($word)) {
throw new InvalidArgumentException("All elements in the array must be strings.");
}
// Sort characters
$chars = str_split($word);
sort($chars);
$sortword = implode('', $chars);
// Group words by their sorted key
if (!array_key_exists($sortword, $map)) {
$map[$sortword] = [];
}
$map[$sortword][] = $word;
}
// Return grouped anagrams as an array of arrays
return array_values($map);
}
try {
$arr = ["eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro"];
$result = groupAnagrams($arr);
// Print result
echo "[\n";
foreach ($result as $group) {
echo " [ ";
for ($i = 0; $i < count($group); $i++) {
echo "'" . $group[$i] . "'";
if ($i + 1 < count($group)) {
echo ", ";
}
}
echo " ]\n";
}
echo "]\n";
} catch (Exception $e) {
// Handle errors
fwrite(STDERR, $e->getMessage() . PHP_EOL);
}
/*
run:
[
[ 'eat', 'tea', 'ate' ],
[ 'rop', 'orp', 'pro' ],
[ 'nat', 'tan' ],
[ 'bat' ]
]
*/