Search code examples
phpdirectoryglob

How to add limit when echoing images from a directory folder?


Below is a script that echoes out all images from a directory folder, it works with no issues. However, I'm simply trying to limit the number of images echoed to 8 or less. Any help is appreciated.

PHP:

$files = glob("images/*.*");
    
for ($i=1; $i<count($files); $i++){
  $image = $files[$i];
  $supported_file = array(
    'gif',
    'jpg',
    'jpeg',
    'png'
  );
    
  $ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
  if (in_array($ext, $supported_file)) {
    echo '<div class="col-md-6 col-xs-4">';   
    echo '<img src="'.$image .'" alt="Random image"  class="your_images" />'."<br /><br />";
    echo '</div>';   
  } else {
    continue;
  }
}


Solution

  • Like Raman allready stated a simple modification to the for will do it

    $maxImages = 8;
    
    for ($i=1; $i<=count($files) && $i<=$maxImages; $i++) {
        // do your stuff
    }
    

    You need to have the image count in case you do not have 8 images in your folder