Question is not very clear: I'm not getting if the OP wants the results grouped by initial letter and sorted, or only obtain the first letter.
Extract first letter from every word in the array
Basic concept
As others stated, a string can be seen also as an array of characters. In this case, we need to take the first character only (at index 0):
$word = 'cat'; $initial_letter = $word[0]; // result: 'c'
Repeat for every item
In order to apply this to every word in the array, we can use array_map(callback, $array) which applies a callback function, to every item in the array.
So:
$my_array = ["Alpha", "Aloo", "Amakeaviral", "Boki", "Bone"]; array_map(fn($word) => $word[0], $my_array); // result: ['A', 'A', 'A', 'B', 'B'];
If you want to return the first letter in uppercase format:
$my_array = ['alpha', 'omega']; array_map(fn($word) => strtoupper($word[0]), $my_array ); // result: ['A', 'O'];
Sort words by initial letter
We can sort/divide the words array into groups, by their initial letter.
This is the expected format: [ 'A' => [word1, word2, word3, ...], 'B' => [word1, word2, ...] ]
$my_array = ["Alpha", "Aloo", "Amakeaviral", "Boki", "Bone"]; $grouped_word_list = []; foreach($my_array as $word) { $word_initial = strtoupper($word[0]); $grouped_word_list[$word_initial][] = $word; }
To sort the result, you can sort the initial array this way:
sort($my_array); // it will modify the original array, don't assign result to a variable
Why sorting the initial array instead of sorting the final list?
- because sorting an unidimensional array is much easier and fast than sorting an associative array
- words will be in the right sequence when they're moved into their group (by initial letter)
Full example
$my_array = [ 'Alpha', 'Amakeaviral', 'Boki', 'Bone', 'Aloo', 'Zeta' ]; // Sort words in the array sort($my_array); // Get words grouped by initials $grouped_word_list = []; foreach ( $my_array as $word ) { $word_initial = strtoupper($word[0]); $grouped_word_list[ $word_initial ][] = $word; } // Print result var_dump($grouped_word_list);
$my_array[$i][0]. Also your loop is wrong it should be$i < count($my_array).