Last active
March 24, 2018 21:10
-
-
Save ahoulgrave/1e74b75a297b224579aa2f5e963b08ee to your computer and use it in GitHub Desktop.
PHP smart pagination
This file contains hidden or 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 | |
/** | |
* @param int $page | |
* @param int $total | |
* @param int $range | |
* | |
* @return array | |
*/ | |
function getPages(int $page, int $total, int $range): array | |
{ | |
if ($total < $range) { | |
return range(1, $total); | |
} | |
$adjacent = floor($range/2); | |
// First pages | |
if ($page <= $range - $adjacent) { | |
$pages = range(1, $range); | |
$pages[] = '...'; | |
$pages[] = $total; | |
return $pages; | |
} | |
// Last pages | |
if ($page >= ($total - $range + $adjacent)) { | |
$pages = range($total - $range, $total); | |
array_unshift($pages, '...'); | |
array_unshift($pages, 1); | |
return $pages; | |
} | |
$pages = range($page - $adjacent, $page + $adjacent); | |
if (reset($pages) > 2) { | |
array_unshift($pages, '...'); | |
} | |
array_unshift($pages, 1); | |
$pages[] = '...'; | |
$pages[] = $total; | |
return $pages; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment