How to group words by first letter in PHP

1 Answer

0 votes
/**
 * Groups words by their first letter.
 *
 * @param array $words  List of words to group
 * @return array        Associative array: letter => list of words
 */
function groupByFirstLetter(array $words): array
{
    $groups = [];  // associative array for grouping

    foreach ($words as $word) {
        // Extract the first character
        $first = strtoupper($word[0]);

        // If the key doesn't exist, create an empty array
        if (!isset($groups[$first])) {
            $groups[$first] = [];
        }

        // Add the word to its group
        $groups[$first][] = $word;
    }

    return $groups;
}

// List of words to group
$words = [
    "Python", "JavaScript", "C", "Java", "C#", "PHP",
    "C++", "Pascal", "SQL", "Rust"
];

$grouped = groupByFirstLetter($words);

// Print each group 
foreach ($grouped as $letter => $group) {
    echo $letter . ": [" . implode(", ", $group) . "]\n";
}

// Print the entire array 
print_r($grouped);



/*
run:

P: [Python, PHP, Pascal]
J: [JavaScript, Java]
C: [C, C#, C++]
S: [SQL]
R: [Rust]
Array
(
    [P] => Array
        (
            [0] => Python
            [1] => PHP
            [2] => Pascal
        )

    [J] => Array
        (
            [0] => JavaScript
            [1] => Java
        )

    [C] => Array
        (
            [0] => C
            [1] => C#
            [2] => C++
        )

    [S] => Array
        (
            [0] => SQL
        )

    [R] => Array
        (
            [0] => Rust
        )

)

*/

 



answered Jan 17 by avibootz
...