Skip to content

Instantly share code, notes, and snippets.

@yosko
Created Dec 18, 2013
Embed
What would you like to do?
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