Jump to content

Pagination of foreach();

Go to solution Solved by ignace,

Recommended Posts

I have a blog with the blog entries in a directory (very unsecure, I know) and on my home page I have a foreach(); function that retrieves all of the files (blog entries) from the entries directory. I've posted so many entries, my homepage is taking a very long time to load. Is there any way to paginate this foreach(); function?


Here is my code

foreach (glob("entries/*.php") as $filename)
    include $filename;
Edited by GrizRule
Link to comment
Share on other sites

  • Solution

$current_page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$items_per_page = 20;
$offset = ($current_page - 1) * $items_per_page;
$items = glob("entries/*.php");
$total_items = count($items);
$total_pages = ceil($total_items / $items_per_page);

foreach (array_slice($items, $offset, $items_per_page) as $entry) {
include $entry;
Edited by ignace
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.