Search code examples
phphtmlmodx

Image gallery from folder with limit of images


I have some code below, but I cant get the array_splice to limit the number of images shown.

<?php
$id = $_GET['id'];
  if (empty($id)) { 
    $clientname = 'tazz';
} else {
    $clientname = $_GET['id'];
}

$total = $_GET['limit'];
  if (empty($total)) { 
    $limit = '100';
} else {
    $limit = $_GET['limit'];
}

$basefolder = "client/client-galleries/";
$dirname = $basefolder.$clientname."/";

    $images = scandir($dirname);
    sort($images);
    //shuffle($images);
    $ignore = array(".", "..");
    $output = array_splice($ignore, 0, $limit);

foreach($images as $curimg) {
        if(!in_array($curimg, $output)) {

echo "
    <div class='gallery'>
        <img src='[[pThumb? &input=`$dirname$curimg` &options=`&w=300&h=300&zc=1&q=95&fltr[]=wmi|./client/images/gallery-watermark-white.png|BL|50|25|200`]]' alt='$curimg'>
        <div class='desc'></div>
    </div>\n ";

        }
    }

This correctly shows the images in the gallery but doesnt limit the amount of images as set by http://website.address?id=client&limit=5


Solution

  • You're not applying array_splice to your $images array, but to your $ignore array, which only contains "." and "..". Also, array_splice is used to search/replace within an array, you're probably looking for array_slice, which is used to get a specific part of an array.

    If you use array_diff to remove unwanted values from $images, you can then use array_slice to only keep at most $limit images. Something like this:

    $images = scandir($dirname);
    $ignore = array(".", "..");
    $images_filtered = array_diff($images, $ignore);
    $images_limited = array_slice($images_filtered, 0, $limit);
    

    $images_filtered should contain all items from $images that are not in $ignore. $images_limited should contain the first $limit items from $images_filtered.