Search code examples
phplimit

Set a limit in the results (no mysql)


Can I put a limit to show in a list of images extracted from a folder? I should point out that I do not mean with mysql but simple php.

Practically from a folder I extract all the images, here, I would like to set a limit. is it possible? or must necessarily the database?


Solution

  • You mention "extracted from a folder" and also "or must necessarily the database" so I'm not sure what your source is.

    If you are getting the list of images them from a folder, presumably using something like glob() or readdir() or scandir() then you end up with an array. If you only want to display a certain number of those images then simply stop after that number of iterations...

    $imgs = glob('*.jpg');
    $count = 0;
    foreach ($imgs as $img) {
        if ($count++ > 20) break; // place a limit of 20
        echo "<img src='$img' alt='$img' />\n";
    }
    

    If you are using a database to obtain your list of image filenames then you would do something similar, controlling it within your loop:

    $sql = "SELECT filename, alt_text FROM ...";
    $conx = mysqli_connect($host, $user, $pass, $dbname, ...);
    $results = mysqli_query($conx, $sql);
    $count = 0;
    while ($row = mysqli_fetch_assoc($conx, $results)) {
        if ($count++ > 20) break; // place a limit of 20
        echo "<img src='$row[filename]' alt='$row[alt_text]' />\n";
    }
    mysqli_free_results($results);
    

    If I have not yet answered your question then please clarify. If I have, please vote for the answer.

    Thanks!