Simple Pagination

By sean
Platform:  PHP
Published  Dec 07, 2010
Updated  Dec 07, 2010
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.

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

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)
Example:

Code

 

HTML Output:

Code

 

Page Output:
1 2 3 4 5 ... next › last » <?php
function handle_pagination($total, $page, $shown, $url) {
$pages = ceil( $total / $shown );
$range_start = ( ($page >= 5) ? ($page - 3) : 1 );
$range_end = ( (($page + 5) > $pages ) ? $pages : ($page + 5) );

if ( $page >= 1 ) {
$r[] = '<span><a href="'. $url .'">&laquo; first</a></span>';
$r[] = '<span><a href="'. $url . ( $page - 1 ) .'">&lsaquo; previous</a></span>';
$r[] = ( ($range_start > 1) ? ' ... ' : '' );
}

if ( $range_end > 1 ) {
foreach(range($range_start, $range_end) as $key => $value) {
if ( $value == ($page + 1) ) $r[] = '<span>'. $value .'</span>';
else $r[] = '<span><a href="'. $url . ($value - 1) .'">'. $value .'</a></span>';
}
}

if ( ( $page + 1 ) < $pages ) {
$r[] = ( ($range_end < $pages) ? ' ... ' : '' );
$r[] = '<span><a href="'. $url . ( $page + 1 ) .'">next &rsaquo;</a></span>';
$r[] = '<span><a href="'. $url . ( $pages - 1 ) .'">last &raquo;</a></span>';
}

return ( (isset($r)) ? '<div>'. implode("\r\n", $r) .'</div>' : '');
}
?>

Comments

Sign in to comment.
sean   -  Dec 10, 2010
Well, I'll certainly commit as much as I can!
I see there's no shortage of MSL contributions lol :)
 Respond  
Hawkee   -  Dec 08, 2010
That's what we've got you for, keep them coming!
 Respond  
sean   -  Dec 08, 2010
Thanks! That's an excellent idea; it was just outside the original scope of the function.
Looks like the PHP activity levels have dropped significantly :(
 Respond  
Hawkee   -  Dec 08, 2010
Great, I have a very similar function that I use all the time here on the site. The only suggestion I have is to make the range adjustable rather than a constant value.
 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.