Adding a simple pagination to your site

or: the dangerousness of simple mathematics

I guess many people had this problem before and I think everybody managed to solve this quite similar. Anyways, just in case this is useful for anybody: here’s how I added a pagination to a site recently.

Given you have an array of products for example. Or maybe search results, a list of articles… something like that. Unfortunately they are too many to display them on a single page. Well, sure, you could but let’s be honest: that isn’t an option as the page would exceed its “scrollable-with-no-harm-to-scroll-fingers” length. And you don’t want to get sued by your visitors, right 😉
Ok, so you’re going to add a nice pagination to your site, so that everybody is happy.
What I found out to be a bit tricky was to calculate the actual number of pages. We need that number so that we know, how many page links we will show next to our current view.

Two simple examples to illustrate the probelm:
Let’s say we have 8 items. 8 divided by 4 is 2, so we’re going to need two pages. No big deal, right?
Okay then we try this with 9 items. 9 divided by 4 gives us 2.25. So we will clearly need a 3rd page for product number 9, but how do we calculate this from our result?

$itemcount = $res->length();
$pagemin = $itemcount / 4;
$pagemax = ceil($itemcount / 4);
if ( $pagemax - intval($pagemin) === 1) ) {
$pages = $pagemax;
} else {
$pages = intval($pagemin);

The code explained

That’s why I compare two values here: the actual division result and the next bigger integer. Now we try to find out if both values differ. If they do, we have a scenario where we do want another page, so we pick the bigger result as our page number. If not we are just happy and use the smaller number.

So now that we know our actual page count we can do something (slightly simplified) like this:

while($i = 0;$i < $pages; $i++) {
print '<a href="?page=' . $i . '">Page ' . $i . '';

A pagination helps to navigate through long lists of items
A pagination helps to navigate through long lists of items

With a little bit of styling this even looks nice. And of course, this is just a start. You also might want to add “previous” and “next buttons”, or those “first page”, “last page” buttons, limit the maximum number of page links shown, or you could center the currently viewed page in the middle, hide the previous button on the first page, etc… There are a lot of fine tuning options that will improve the user experience of your pagination.

About Erik

This cool kid's name is Erik Pöhler. I am a media designer and making websites is my profession. I started my private blog in 2005 and since that I worked in Rosenheim, Los Angeles, California and, for no good reason, moved back to Karlsruhe, Germany recently.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply