Ok I’ve got PHP to successfully open and read the contents of a directory containing a number of images. I pass all of this data into an array, sort the results and finally iterate over all of the images so that it gives me a sting which I then echo onto the html page. In this string I set the css class for each div so that when the page renders each div is displayed correctly.
My question is to do with the actual PHP setting the class of each div. Basically I have two classes that I apply to each div depending on what number they are. For example in the first horizontal row, the 1st to 3rd div gets the class of .box so as to set a margin-right:10px; and the 4th get’s it’s own class of .box last which sets margin-right:0px;.
So what I wanted to ask was is there way of writing some logic to tell the PHP code to apply one class for the 1st to 3rd divs and a separate class for every 4th div for each row?Effectively the first three divs in the row get on class and the fourth div in each row gets another?
<?php
$dir = "images/";
$images = array();
$returnstr = "";
if ($handle = opendir($dir)) {
while ( false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != ".."){
$images[] = $entry;
}
}
closedir($handle);
}
natsort($images);
$newArray = array_values($images);
foreach ($newArray as $key => $value) {
$returnstr .= '<li class="box">';
$returnstr .= '<a href="#" name="" class="thumb" id="' . $key . '"><img src="'. $dir . '/' . $value . '"/></a>';
$returnstr .= '</li>';
}
?>
This is the CSS for the 1st – 3rd divs…
.box {
float: left;
/*margin-right:10.5px;*/
margin-right:10px;
/*width: 92px;
height: 92px; */
width: 232.5px;
height:150px;
/*height: 232px; */
/*background-color: #999;
border: 1px solid*/
margin-bottom: 10px;
list-style: none;
}
… and the CSS for every 4th div in the grid
.box.last {
margin-right: 0px;
}
This is the html I trying to atchieve.
<li class="box">
<a href="#" name="cap1" class="thumb" id=""><img src="images/1.jpg"/></a>
</li>
<li class="box">
<a href="#" name="cap2" class="thumb" id=""><img src="images/2.jpg"/></a>
</li>
<li class="box">
<a href="#" name="cap3" class="thumb" id=""><img src="images/3.jpg"/></a>
</li>
<li class="box last">
<a href="#" name="cap4" class="thumb" id=""><img src="images/4.jpg"/></a>
</li>
You can do this using the modulus operator, %, along with an integer that you increment each time through the loop. Simple example: