How to display an Array under alphabetical letters using PHP?

后端 未结 6 1984
傲寒
傲寒 2021-02-04 17:06

I have an array that already contains all it\'s values in alphabetical order:

Alligator
Alpha
Bear
Bees
Banana
Cat
Cougar

Now I just want to li

6条回答
  •  太阳男子
    2021-02-04 17:32

    Iterate through the array and check if the current item starts with another letter than the previous one. If that's the case print your "A ---".

    $currentLetter = '';
    foreach ($list as $item) {
       $firstLetter = substr($item, 0, 1);
       if ($firstLetter !== $currentLetter) {
          echo $firstLetter . "\n---\n";
          $currentLetter = $firstLetter;
       }
       echo $item . "\n";
    }
    

提交回复
热议问题