PHP: Simple Pagination

Sean Wragg
Dec 8, 2010 · 1 min read

This is a simple pagination snippet I wrote for a Drupal module I was working on. I’ve “unDruaplized” it and now it’s completely independent.

The function will calculate the number of pages to display based on $total and $shown. In addition, it'll append the corresponding page number to the provided $url.

This function takes 4 params:

  • (int) $total - total number of results. 100 in our example
  • (int) $page - the page number you're currently on. using $_GET['p'] in our example
  • (int) $shown - number results to display per page. 10 results per page in our example
  • (str) $url - the url each link should have. ?p= in our example

100(results) / 10(per page) = 10(pages)

NOTE: All page numbers are incremented by one. This means, the function assumes URL 0 as page 1.

Example Usage:

echo handle_pagination(100, (int)$_GET['p'], 10, '?p=');

HTML Output

The following is an example of the markup our snippet below will generate

Which should produce something like the following:

1 2 3 4 5 ... next › last »


Code, Comics, and Fhqwhgads!

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store