Creating divs with loop but different classes

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tonchily
Forum Commoner
Posts: 54
Joined: Thu Sep 02, 2010 10:44 am

Creating divs with loop but different classes

Post by tonchily »

For example I got a mysql table with columns ID (which is autoincerement) and name. I got 5 entries with values "John", "Mike", "Brian", "Tony", "Luke".
I want to make a loop create divs with different classes and repeat it all the time when new entries are added. The html code would look like

<div class="white">John</div> <br />
<div class="black">Mike</div> <br />
<div class="white">Brian</div> <br />
<div class="black">Tony</div> <br />
<div class="white">Luke</div> <br />


How can I accomplish this?
s992
Forum Contributor
Posts: 124
Joined: Wed Oct 27, 2010 3:06 pm

Re: Creating divs with loop but different classes

Post by s992 »

This will do it, not sure if there's a better way, though.

Code: Select all

<?php

$names = array('John','Mike','Brian','Tony','Luke');
$i = 0; // We're going to use $i to count our iterations

// Loop through the array of names(or your query)
foreach($names as $name) {
	// If the remainder of $i/2 is 0, give it a class of white. Otherwise,
	// give it a class of black.
	echo ($i % 2 == 0) ? '<div class="white">' : '<div class="black">';
	// Echo the name
	echo $name;
	// Close the div
	echo "</div>";
	// Increment our count
	$i++;
}

?>
Neilos
Forum Contributor
Posts: 179
Joined: Fri Nov 19, 2010 2:07 am

Re: Creating divs with loop but different classes

Post by Neilos »

s992's way works with alternating white and black, if you want to have more classes you'll want to use an array.

Make an array using the values for the classes eg (if they just . Then pull the records and create an array of the records.

If they both are 5 values long then;

Code: Select all

<?php

// have some query that gets back an array ($names) containing the 5 names in the order you want

$classes[0] = "white";
$classes[1] = "black";
$classes[2] = "white";
$classes[3] = "black";
$classes[4] = "white"; // these can be changed to whatever you want

$i=0;

foreach ($classes as $value) {

echo '<div class="' . $value . '">' . $names[$i] . '</div>'; 

$i++;

}

?>
Post Reply