Skip to content

Instantly share code, notes, and snippets.

@jerrac
Created January 6, 2023 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jerrac/b2be8beb1d3801ee7861aba5bf1ba3e3 to your computer and use it in GitHub Desktop.
Save jerrac/b2be8beb1d3801ee7861aba5bf1ba3e3 to your computer and use it in GitHub Desktop.
A simple pagination function in php.
<?php
public static function paginate(int $totalItems, int $offset, int $size)
{
$pages = [];
$i = 0;
$pageNumber = 1;
while ($i <= ($totalItems - $size)) {
$page['number'] = $pageNumber;
$page['offset'] = $i;
$page['size'] = $size;
$page['first_page'] = false;
$page['last_page'] = false;
if ($i === $offset) {
$page['current'] = true;
} else {
$page['current'] = false;
}
$pages[] = $page;
$pageNumber++;
$i = $i + $size;
}
$pages[0]['first_page'] = true;
$pages[count($pages) - 1]['last_page'] = true;
// Limit how many page numbers we show.
$pageCount = count($pages);
if ($pageCount > 15) {
$firstPage = [$pages[0]];
$lastPage = [$pages[$pageCount - 1]];
$firstFive = array_slice($pages, 0, 5, true);
$lastFive = array_slice($pages, $pageCount - 5, 5, true);
$currentPage = $offset / $size;
if ($offset !== 0 && !($offset >= ($totalItems - (5 * $size)))) {
$middleFive = array_slice($pages, $currentPage - 2, 5, true);
$middleThree = array_slice($pages, $currentPage - 1, 3, true);
} else {
$middleFive = array_slice(
$pages,
ceil(($pageCount / 2) - 2),
5,
true
);
$middleThree = array_slice(
$pages,
ceil(($pageCount / 2) - 1),
3,
true
);
}
$dotsOne = ['dotsOne' => '...'];
$dotsTwo = ['dotsTwo' => '...'];
if (($offset <= ($size * 4))) {
$listOfPages = array_merge(
$firstFive,
$dotsOne,
$middleThree,
$dotsTwo,
$lastPage
);
} elseif ((($offset + ($size * 5)) >= $totalItems)) {
$listOfPages = array_merge(
$firstPage,
$dotsOne,
$middleThree,
$dotsTwo,
$lastFive
);
} else {
$listOfPages = array_merge(
$firstPage,
$dotsOne,
$middleFive,
$dotsTwo,
$lastPage
);
}
return $listOfPages;
} else {
return $pages;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment