Arrange an array by the first letter

Long time, no post 🙂
Here is a small PHP tips&tricks post : we have an array full of values, let’s say a country list (in this example the list is limited, we don’t want to see 190+ values).

Array
(
    [0] => Array
        (
            [0] => Afghanistan
            [name] => Afghanistan
            [1] => AF
            [code] => AF
        )

    [1] => Array
        (
            [0] => Albania
            [name] => Albania
            [1] => AL
            [code] => AL
        )

    [2] => Array
        (
            [0] => Algeria
            [name] => Algeria
            [1] => DZ
            [code] => DZ
        )

  
    [3] => Array
        (
            [0] => Bangladesh
            [name] => Bangladesh
            [1] => BD
            [code] => BD
        )

    [4] => Array
        (
            [0] => Barbados
            [name] => Barbados
            [1] => BB
            [code] => BB
        )

   
    [5] => Array
        (
            [0] => Belgium
            [name] => Belgium
            [1] => BE
            [code] => BE
        )


    [6] => Array
        (
            [0] => Brazil
            [name] => Brazil
            [1] => BR
            [code] => BR
        )


    [7] => Array
        (
            [0] => Cape Verde
            [name] => Cape Verde
            [1] => CV
            [code] => CV
        )

    [8] => Array
        (
            [0] => Cayman Islands
            [name] => Cayman Islands
            [1] => KY
            [code] => KY
        )
)

and we want to display like this

-A-
  • Afghanistan
  • Albania
  • Algeria
-B-
  • Bangladesh
  • Barbados
  • Belgium
  • Brazil
-C-
  • Cape Verde
  • Cayman Islands

, the right and easy way to do this would be to retain in a variable the first letter of the last country and in another variable the first letter of the current country. We compare them and if they are different we just output the first letter and then the name of the current country. All this in just few and simple to understand lines, right? 😛

//try to do the A-Z list
$v = function to get your country list from a DB sorted by country name!;
$last_letter = '';
$current_letter = '';
for ($i=0;$i" . $current_letter . "
"; } print $v[$i]["name"] . "
"; $last_letter = $current_letter; }

I hope this will help someone 😉

Revision
09.12.2007, 12:09 : added “sorted by country name!” comment in the php code example. Thanks to Dragos.