Search code examples
phparraysloopsalphabetical

Echoing Array in an A-Z List


Say I have the following array:

$aTest = array('apple', 'pear', 'banana', 'kiwi', 'pineapple', 'strawberry');

I need to be able to create a list from A-Z and show the relevant values from the array under each letter. E.g A - Apple, B - Banana, C - empty, D - empty, ... K - Kiwi .. P - Pear, Pineapple etc.

Can someone please help me? I assume I loop from A-Z using range but then im not sure how to echo out the relevant value from the array(and also in alphabetical order within each letter i.e pear before pineapple)

Thanks


Solution

  • Through the use of conditionals and some built-in functions; this code is a little rough, but it does the trick:

    <?php
        $aTest=array('apple','pear','banana','kiwi','pineapple','strawberry');
        $len=(count($aTest)-1);
        $letters=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
        $str=null;
        foreach($letters as $letter) {
            for($i=0;$i<=$len;$i++) {
                $str=strtoupper($letter).' - ';
                if(strtolower(substr($aTest[$i],0,1))==strtolower($letter)) {
                    $str.=$aTest[$i];
                    break;
                } elseif($i==$len) {
                    $str.='empty';
                }
            }
            echo($str.'<br />');
        }
    ?>