1

Here is my code ( I have an external JS and jQuery file linked, and my folder for images is called uploads/):

So, currently this shows all images I upload. What I want is to have a limit on how many images it shows.

I want to limit this to allow only to show the last 4 images. Is there a way? Thanks!

<?php include("header.inc"); ?>

<?php include("nav.inc"); ?>


<?php
    $files = scandir("uploads/");
?>

    <div id="myCarousel" class="carousel slide" data-ride="carousel">
      <!-- Indicators -->
      <ol class="carousel-indicators">

          <?php
              $i = 0;
              for($a = 2; $a < count($files); $a++):
          ?>

        <li data-target="#myCarousel" data-slide-to="<?php echo $i; ?>" class="<?php echo $i == 0 ? 'active': ''; ?>"></li>

          <?php
              $i++;
              endfor;
          ?>

      </ol>

      <!-- Wrapper for slides -->
      <div class="carousel-inner">

          <?php
              $i = 0;
              for($a = 2; $a < count($files); $a++):
          ?>

        <div class="item <?php echo $i == 0 ? 'active': ''; ?>" align="center">
          <img src="uploads/<?php echo $files[$a]; ?>" style="width: 640px; height: 640px;">
        </div>

          <?php
              $i++;
              endfor;
          ?>

      </div>

      <!-- Left and right controls -->
      <a class="left carousel-control" href="#myCarousel" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left"></span>
        <span class="sr-only">Previous</span>
      </a>
      <a class="right carousel-control" href="#myCarousel" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right"></span>
        <span class="sr-only">Next</span>
      </a>
    </div>

<?php include("footer.inc"); ?>

<!-- end snippet -->

roshnet
  • 1,695
  • 18
  • 22
Andrew
  • 176
  • 1
  • 14
  • After you do $files = scandir("uploads/"); you should filter the files array as per your needs (getting the latest 4 modified files in your case). eg: https://www.jonasjohn.de/snippets/php/listdir-by-date.htm – Jaspal Singh Oct 27 '19 at 06:58

1 Answers1

1

Replace:

$files = scandir("uploads/");

with:

const CAROUSEL_LENGTH = 4;   // Should be on top of script or in a config file
$files = array_slice(scandir('uploads/', SCANDIR_SORT_DESCENDING), 0, CAROUSEL_LENGTH);

The SCANDIR_SORT_DESCENDING flag will sort files by timestamp (see this post for a more in-depth explanation) and array_slice will take the first four.

Jeto
  • 14,596
  • 2
  • 32
  • 46