Creating pagination links in PHP

When displaying a large amount of content, pagination — splitting the content into separate pages — can improve usability. Pagination links allow the visitor to move between the different pages, but can make browsing difficult if implemented poorly. PaginationLinks is a PHP class that aids in creating effective pagination links.

Download PaginationLinks

Download the file below and upload it to your web server.

File Size Description
class.PaginationLinks.php 3,715 bytes PHP class

Using PaginationLinks

Links can be created using the static create function of the PaginationLinks class. The function takes up to six parameters, but only two are required: the current page number, and the number of pages. For example:

1
2
3
4
5
// include the PaginationLinks class
require_once './class.PaginationLinks.php';

// output the links for page 5 of 9
echo PaginationLinks::create(5, 9);

This outputs the following links:

1 24 5 68 9

The links include the first page, the current page, the last page, and one page either side of each of these for context, with the omitted pages being represented by ellipses (the ‘...’ symbols). The amount of context can be controlled using the optional third parameter, which defaults to 1:

1
2
3
4
5
// include the PaginationLinks class
require_once './class.PaginationLinks.php';

// output the links for page 3 of 9, with two pages of context
echo PaginationLinks::create(3, 9, 2);

This outputs the following links:

1 2 3 4 57 8 9

Note that this list includes only a single ellipsis as there are no omitted pages between the first page and current page.

Customising the HTML

When called with two or three parameters, the create function produces HTML in the following format:

1
2
3
4
5
6
7
8
9
<a href="?page=1">1</a>
<a href="?page=2">2</a>
&hellip;
<a href="?page=4">4</a>
<span>5</span>
<a href="?page=6">6</a>
&hellip;
<a href="?page=8">7</a>
<a href="?page=9">9</a>

Each page link sets the GET parameter page to the page number, the current page number is within a span element, and omitted pages are represented by the character entity reference for an ellipsis.

The remaining three parameters can be used to override this default formatting. The fourth and fifth parameters provide templates for the links and the current page respectively. These are used as parameters for the PHP sprintf function, and so occurrences of %d will be replaced by the page number. The sixth parameter provides a string to use as the ellipsis. For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// include the PaginationLinks class
require_once './class.PaginationLinks.php';

// output the links for page 5 of 9, with custom formatting
echo PaginationLinks::create(
    5,
    9,
    1,
    '<a href="?page=%d">[%d]</a>',
    '[%d]',
    '&mdash;');

This outputs the following links:

[1] [2][4] [5] [6][8] [9]

Where now?

Found this useful? Share it:

Also in PHP: