Outputting images in folder and clearing float After Every 6 Returned In Loop in PHP
I'm trying to count the images in my folder and want to clear the float after each 6 images returned from a folder. Here's the code I've got so far but it spits out the clear more than the amount I'd like for it. Could somebody maybe guide me to a solution? Thanks in advance. Below is my code.
<?php
$i = 0;
$dirname = "images";
$images = scandir($dirname);
$filecount = count(glob("images/". "*.png"));
//echo $filecount;
$ignore = Arra开发者_开发问答y(".", "..", "otherfiletoignore");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
if ($i % 6 === 0){
echo "<div style='clear:both;></div>'";
}
echo "<div style='float:left;'><img src='images/",$curimg."'"," /></div>";
}
}
?>
You're not ever changing the value of $i
, therefore it will be zero every time through the loop. In this situation you want to use a for
loop instead of a foreach
loop.
$images = glob("images/*.png");
$filecount = count($images);
$ignore = Array(".", "..", "otherfiletoignore");
for ($i = 0; $i < $filecount; $i++){
if(!in_array($images[$i], $ignore)) {
if ($i % 6 === 0){
echo "<div style='clear:both;></div>'";
}
echo "<div style='float:left;'><img src='images/",$images[$i]."'"," /></div>";
}
}
This code will spit out the line echo "<div style='clear:both;></div>'";
on every iteration. This is because you have not incremented $i
anywhere. $i % 6 === 0
will always be true because $i
is always zero.
Change:
if(!in_array($curimg, $ignore)) {
if ($i % 6 === 0){
...to:
if(!in_array($curimg, $ignore)) {
$i++;
if ($i % 6 === 0){
...or use a for
loop instead of foreach
.
精彩评论