To categorize a list of items in PHP by their first letter, you can iterate through the list and group the items into a new associative array, where the keys are the first letters and the values are arrays of items that begin with that letter.
Here is an example:
<?php
$items = [
"Apple",
"Banana",
"Cherry",
"Date",
"Apricot",
"Blueberry",
"Carrot",
"Dragonfruit"
];
$groupedItems = [];
foreach ($items as $item) {
$firstLetter = strtoupper(substr($item, 0, 1)); // Get the first letter and convert to uppercase
// If the first letter key doesn't exist in $groupedItems, create an empty array for it
if (!isset($groupedItems[$firstLetter])) {
$groupedItems[$firstLetter] = [];
}
// Add the current item to the array corresponding to its first letter
$groupedItems[$firstLetter][] = $item;
}
// Optional: Sort the grouped items by their first letter (key)
ksort($groupedItems);
// Output the grouped items for demonstration
foreach ($groupedItems as $letter => $itemsInGroup) {
echo "<h2>" . $letter . "</h2>";
echo "<ul>";
foreach ($itemsInGroup as $item) {
echo "<li>" . $item . "</li>";
}
echo "</ul>";
} ?>
For Cyrillic text, replace substr() with mb_substr(). This is necessary for handling strings that use multibyte encodings. In Unicode, Russian characters take up 2 bytes, while Latin characters and spaces take up 1 byte.