Skip to content

Instantly share code, notes, and snippets.

@yosko
Created December 18, 2013 10:29
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 yosko/8020218 to your computer and use it in GitHub Desktop.
Save yosko/8020218 to your computer and use it in GitHub Desktop.
PHP function to help generate an HTML pagination system.
<div class="pagination">
<?php
foreach($pagination as $key => $value) {
if($value == 'current') {
echo '<span>'.$key.'</span>';
} else {
if($value == 'last')
echo '&hellip;';
echo '<a href="path/to/my/list/'.$key.'">';
if($value == 'first')
echo '&laquo;';
elseif($value == 'last')
echo '&raquo;';
else
echo $key;
}
if($value == 'first')
echo '&hellip;';
}
?>
</div>
<?php
/**
* Generate an array of pagination link where the key is a page number
* and the value is a type of link (current page, normal link, first/last page link)
* @param integer $currentPage the current displayed page
* @param integer $totalPages the total number of pages (can be replaced by the two following params)
* @param integer $itemPerPage the number of item displayed on each page
* @param integer $totalItems the total number of existing items
* @param integer $nbPagesAround the maximum number of links (excluding first/last) that should be displayed before or after the current page
* @return array the pagination array (key = page to link to, value = type of link)
*/
function generatePagination(
$currentPage,
$totalPages = 0,
$itemPerPage = 0,
$totalItems = 0,
$nbPagesAround = 2
) {
$pagination = array();
if($totalPages == 0) {
if($itemPerPage == 0 || $totalItems == 0) {
return false;
} else {
$totalPages = (int)ceil($totalItems / $itemPerPage);
}
}
if($currentPage > $nbPagesAround + 2) {
$pagination[1] = self::PAGINATION_FIRST;
} elseif($currentPage > $nbPagesAround + 1) {
$pagination[1] = self::PAGINATION_LINK;
}
for($i = ($currentPage - $nbPagesAround); $i < $currentPage; $i++) {
if($i > 1 || ($i == 1 && $currentPage <= $nbPagesAround + 1)) {
$pagination[$i] = self::PAGINATION_LINK;
}
}
$pagination[$currentPage] = self::PAGINATION_CURRENT;
for($i = ($currentPage + 1); $i < ($currentPage + $nbPagesAround + 1); $i++) {
if($i < $totalPages
|| ($i == $totalPages && $currentPage >= $totalPages - $nbPagesAround)
) {
$pagination[$i] = self::PAGINATION_LINK;
}
}
if($currentPage < ($totalPages - $nbPagesAround - 1)) {
$pagination[$totalPages] = self::PAGINATION_LAST;
} elseif($currentPage < ($totalPages - $nbPagesAround)) {
$pagination[$totalPages] = self::PAGINATION_LINK;
}
// ksort($pagination);
return $pagination;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment