How can I improve this PHP pagination algorithm?

chulataxing

New Member
I'm working on a pagination algorithm in PHP. I can guess that it needs room for improvement, so I'd like some thoughts on how to improve it, be it cleaning up the code itself, from a UI/UX standpoint, or anything else you can think of.The algorithm should output pagination that looks like this:\[code\]1 2 3 ... 6 7 8 ... 97 98 99\[/code\]or this:\[code\]1 2 3 4 5 ... 6 7 8 9 10\[/code\]or this: \[code\]1 2 3\[/code\]Here's my code: \[code\]<?phpif(!is_null($_GET['page'])) { $currentPage = $_GET['page'];} else { $currentPage = 1;}if($pages != null) { echo 'Page: ';}// Less than 10 pagesif($pages <= 10) { for($page = 1; $page <= $pages; $page++) { echo '<a href="http://stackoverflow.com/questions/3744794/?page=' . $page . '">' . $page . '</a> '; }// Greater than 10 pages, and we're somewhere in the middle of them} elseif(($pages > 10) && ($currentPage > 4) && ($currentPage < $pages - 3)) { for($page = 1; $page <= 3; $page++) { echo '<a href="http://stackoverflow.com/questions/3744794/?page=' . $page . '">' . $page . '</a> '; } echo '... '; for($page = $currentPage - 1; $page <= $currentPage + 1; $page++) { echo '<a href="http://stackoverflow.com/questions/3744794/?page=' . $page . '">' . $page . '</a> '; } echo '... '; for($page = $pages - 2; $page <= $pages; $page++) { echo '<a href="http://stackoverflow.com/questions/3744794/?page=' . $page . '">' . $page . '</a> '; }// Greater than 10 pages, and we're towards the end of the pages} else { for($page = 1; $page <= 5; $page++) { echo '<a href="http://stackoverflow.com/questions/3744794/?page=' . $page . '">' . $page . '</a> '; } echo '... '; for($page = $pages - 5; $page <= $pages; $page++) { echo '<a href="http://stackoverflow.com/questions/3744794/?page=' . $page . '">' . $page . '</a> '; }}\[/code\]
 
Back
Top