Showing posts with label php iterate alphabet. Show all posts
Showing posts with label php iterate alphabet. Show all posts

Saturday, April 30, 2011

PHP To Loop Through Alphabet & Display Categories

The alphabet can be incremented in PHP like numbers can, so incrementing through an alphabetical list is possible.

$capital="A";
$capital++;
echo $capital;
(returns b)

To write all 26 letters of the alphabet
$capital=A;
for ($i=1; $i<=26; $i++)
{
echo $capital;
$capital++;
}
(returns whole alphabet)

I wanted to display categories, in divs, in alphabetical order, querying a database to get categories beginning with each letter, to display in the div corresponding to that letter.

It ends up looking like this...



I set css properties for the divs as follows..
.prop{
height:200px;
float:right;
width:1px;
display:inline;
padding:5px;
margin:5px;
float:left;
width:160px;
border-style:solid;
border-width:2px;
border-color:#2491EE;
}

The php I did as follows...


$capital=A;
for ($i=1; $i<=26; $i++)

{
/*echoes the current letter, images could be used if named A.jpg B.jpg etc*/

echo "<div class=\"prop\"> <strong>".$capital."</strong><br />";

/*The mysql quries a category table returning all categories beginning the current letter*/
$result=mysql_query("SELECT category FROM categories WHERE category REGEXP '^".$capital."' ORDER BY category") or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$cat= $row['category'];

/*the following line echoes the category name and links to a category page, passing the name as a variable*/
echo "<a href='category.htm?category=$cat'>".$cat."</a><br />";
}
echo "</div>";
$capital++;
}