How can you automatically generate alphabet headers for each letter in a sorted list in PHP?

To automatically generate alphabet headers for each letter in a sorted list in PHP, you can iterate through the sorted list and keep track of the current letter. Whenever the current letter changes, you can output a new alphabet header.

<?php
$sortedList = ['Apple', 'Banana', 'Cherry', 'Grape', 'Kiwi', 'Mango', 'Orange', 'Pear', 'Pineapple', 'Strawberry'];

$currentLetter = '';
foreach ($sortedList as $item) {
    $firstLetter = strtoupper(substr($item, 0, 1));
    
    if ($firstLetter !== $currentLetter) {
        echo "<h2>$firstLetter</h2>";
        $currentLetter = $firstLetter;
    }
    
    echo "<p>$item</p>";
}
?>