How to display an Array under alphabetical letters using PHP?

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 !==.


here is another simple solution:-

$result = array();
foreach ($list as $item) {
    $firstLetter = substr($item, 0, 1);
    $result[$firstLetter][] = $item;
}

echo "<pre>"; print_r($result);

Output :-

Array (
[A] => Array
    (
        [0] => Alligator
        [1] => Alpha
    )

[B] => Array
    (
        [0] => Bear
        [1] => Bees
        [2] => Banana
    )

[C] => Array
    (
        [0] => Cat
        [1] => Cougar
    )
 )

Tags:

Php