-
-
Save SeanJA/429886 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//this would come from a database count function | |
$totalPages = 200; | |
//presumably this comes from the get variable | |
$currentPage = 20; | |
//if the current page > total pages, just set it to the number of pages, | |
//someone is messing with the url | |
if ($currentPage > $totalPages) { | |
$currentPage = $totalPages; | |
} | |
// 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. | |
$pager = '<ul class="pager">' . PHP_EOL; | |
$start = 1; | |
if ($currentPage > 2) { | |
$start = $currentPage - 2; | |
} | |
//we can start by assuming that the page is start + 4 because we want to show 5 | |
$end = $start + 4; | |
if ($end > $totalPages) { | |
$end = $totalPages; | |
} else if ($end == $totalPages && $start > 2) { | |
$diff = $totalPages - $currentPage; | |
$start -= ( 2 - $diff); | |
} else if ($start == 1 && $end < $totalPages) { | |
$diff = $currentPage - 1; | |
$end += ( 2 - $diff); | |
} | |
if ($start > 1) { | |
$pager .= '<li><a href="/1">« First</a></li>' . PHP_EOL; | |
$prev = $currentPage - 1; | |
$pager .= '<li><a href="/' . $prev . '">‹ Previous</a></li>' . PHP_EOL; | |
$pager .= '<li>...</li>' . PHP_EOL; | |
} | |
for ($i = $start; $i<=$end; $i++) { | |
$pager .= '<li><a '; | |
if ($currentPage == $i) { | |
$pager .= 'class="current" '; | |
} | |
$pager .= 'href="/' . $i . '">' . $i . '</a></li>' . PHP_EOL; | |
} | |
if ($end < $totalPages) { | |
$pager .= '<li>...</li>' . PHP_EOL; | |
$pager .= '<li><a href="/' . ++$currentPage . '">Next ›</a></li>' . PHP_EOL; | |
$pager .= '<li><a href=/"' . $totalPages . '">Last »</a></li>' . PHP_EOL; | |
} | |
$pager .= '</ul>'; | |
echo $pager; |
PHP_EOL isn't really needed here, I added it so I would not have to scroll to the right to see if I finally got my solution correct (since I was printing it out on the command line).
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also there is DIRECTORY_SEPARATOR (which I usually define as DS since I end up using it a lot... and PATH_SEPARATOR which is important if you are adding things to the path (unix and windows can have different path separators).