Skip to content
Advertisement

PHP loop to output image gallery in Bootstrap with four thumbnails per row

Ok so I’ve been trying to find a definitive answer to this question and have not found one – so please do not mark this as a duplicate because none of the answers on here have worked for me.

I have a simple set of images and the locations stored in a database table. I want to output them using PHP. I know all the MYSQL statements etc for doing this, however I can’t seem to output one row with 4 thumbnails, close the row off then start all over again. I’ve tried using this so called count marker but to no avail. My code is very little I’m afraid but I’m pulling my hair out here.

<?php
    $count = 0;
    echo '<div class="row">';
    for($i=0; $i < 4; $i++) {
        echo '<div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>';
    }
    echo '</div>';
    $count++;
?>

I’m using the placeholder as an example. Has anybody actually solved this problem so it clear and precise? I do not see where to put the count variable in to the right place or is there an if statement that should be in there somewhere?

Please somebody help. As I said I’m literally at the end of my tether now.

Advertisement

Answer

Edited answer:

<?php

$count_items = 12;

$columns = 4;

echo '<div class="row">';
for($i = 0; $i < $count_items; $i++) {
  if($i % $columns === 0 && $i > 0) {
    echo '</div><div class="row">';
  }
  echo '<div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>';
}
echo '</div>';

Outputs:

<div class="row">
  <div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>
  <div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>
  <div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>
  <div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>
</div>
<div class="row">
  <div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>
  <div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>
  <div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>
  <div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>
</div>
<div class="row">
  <div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>
  <div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>
  <div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>
  <div class="col-md-3 text-center"><img src="https://via.placeholder.com/150" alt=""></div>
</div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement