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?
Creating divs with loop but different classes
Moderator: General Moderators
Re: Creating divs with loop but different classes
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++;
}
?>
Re: Creating divs with loop but different classes
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;
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++;
}
?>