Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,689 questions

55,442 answers

573 users

How to convert an array of strings and group all the anagrams into subarrays in PHP

1 Answer

0 votes
// 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' ]
]

*/

 



answered Nov 15, 2025 by avibootz
...