Skip to content

Instantly share code, notes, and snippets.

@gavinblair
Created June 7, 2010 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gavinblair/428807 to your computer and use it in GitHub Desktop.
Save gavinblair/428807 to your computer and use it in GitHub Desktop.
Pagination Display
<ul class='pager'>
<?php
//The goal is to have a pager showing (if available) 5 numbers,
//with the current page number in the middle, if available.
// <<First and <Previous are shown if you can't see page 1,
// and Next> and Last>> are shown if you can't see the last page.
$start = $currentpage <= 2 ? 1 : $currentpage - 2;
$end = $currentpage > ($totalpages - 2) ? $totalpages : $currentpage + 2;
if ($end == $totalpages && $start > 2) {
$diff = $totalpages - $currentpage;
$start -= (2 - $diff);
} else if ($start == 1 && $end < $totalpages) {
$diff = $currentpage - 1;
$end += (2 - $diff);
}
if ($end > $totalpages) { $end = $totalpages; }
if (($end - $start) < 4) { $start = 1; }
if ($start > 1) {
echo "<li><a href='/1'>&laquo; First</a></li>";
$prev = $currentpage - 1;
echo "<li><a href='/$prev'>&lsaquo; Previous</a></li>";
}
for($i=$start; $i<=$end; $i++) {
echo "<li><a ";
echo $currentpage == $i ? "class='current' " : "";
echo "href='/$i'>$i</a></li>";
}
if($end < $totalpages) {
$next = $currentpage + 1;
echo "<li><a href='/$next'>Next &rsaquo;</a></li>";
echo "<li><a href='/$totalpages'>Last &raquo;</a></li>";
}
?>
</ul>
@gavinblair
Copy link
Author

There has to be a nicer formula to accomplish this.

@gavinblair
Copy link
Author

The first half of this is just trying to get the correct $start and $end numbers. This is the part that could use some optimization.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment