Print alphabetical navigation list from an array
I have an array of items and I am trying to generate an alphabetical
navigation for them.
A|B|C|D|E|F|G|H etc...
Apple
Apricot
Carrot
Camel
Dog
So I want to list every letter of the alphabet but only link the ones that
have matching items in the array.
So far I have:
$productArr = array('Apple','Apricot','Carrot','Camel','Dog');
$previous = null;
foreach(range('A','Z') as $alpha) {
$arrayCount = count($productArr);
for ($i=0; $i < $arrayCount; $i++) {
$firstLetter = $productArr[$i];
if ($firstLetter[0] == $alpha && $firstLetter[0] != $previous){
echo '<li><a href="#'.$alpha.'">'.$alpha.'</a></li>';
$previous = $alpha;
}elseif ($firstLetter[0] != $alpha && $alpha != $previous){
echo '<li>'.$alpha.'</li>';
$previous = $alpha;
}
}
}
It works fine up until the elseif, if you comment out the elseif it prints
the list of links as expected. Just need to work out how to print the rest
of the alphabet.
Any help as to where I'm going wrong would be appreciated.
Cheers
No comments:
Post a Comment