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>";
}
?>
Related Questions
- What are some potential pitfalls to be aware of when integrating a MySQL database with PHP for a library system?
- What are the best practices for integrating external resources, like icons, into a PHP project without using multiple package managers?
- What are some best practices for expanding and modifying arrays in PHP when performing calculations like multiplication?