How to display an Array under alphabetical letters using PHP?

后端 未结 6 1987
傲寒
傲寒 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:33

    The solution is to keep in a variable the first letter of the previously printed word, like:

    $previous = null;
    foreach($array as $value) {
        $firstLetter = substr($value, 0, 1);
        if($previous !== $firstLetter) echo "\n".$firstLetter."\n---\n\n";
        $previous = $firstLetter;
    
        echo $value."\n";
    }
    

    NB: if some entries start with a lower-case letter and others with upper-case letters, use the strcasecmp function in the test instead of !==.

提交回复
热议问题