Skip to content

Instantly share code, notes, and snippets.

@bizsimon
Last active July 2, 2020 21:36
Show Gist options
  • Save bizsimon/30d52a82309a2161d9c89ef214d12f04 to your computer and use it in GitHub Desktop.
Save bizsimon/30d52a82309a2161d9c89ef214d12f04 to your computer and use it in GitHub Desktop.
Simple Pagination in PHP
/**
* Simple Pagination function with range dots
* Based on https://gist.github.com/kottenator/9d936eb3e4e3c3e02598
* All credits go to https://gist.github.com/kottenator
*
* @param $curPage
* @param $lastPage
* @param int $delta
* @return array
*/
function pagination($curPage, $lastPage, $delta = 2) {
$left = $curPage - $delta;
$right = $curPage + $delta + 1;
$range = [];
$rangeWithDots = [];
for ($i = 1; $i <= $lastPage; $i++) {
if ($i == 1 || $i == $lastPage || ($i >= $left && $i < $right)) {
$range[] = $i;
}
}
$l = null;
foreach ($range as $i) {
if ($l) {
if ($i - $l === 2) {
$rangeWithDots[] = $l + 1;
} elseif ($i - $l !== 1) {
$rangeWithDots[] = '...';
}
}
$rangeWithDots[] = $i;
$l = $i;
}
return $rangeWithDots;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment