Skip to content

Instantly share code, notes, and snippets.

@brendonexus
Forked from mrl22/pagination.php
Created June 30, 2017 07:49
Show Gist options
  • Save brendonexus/11d241087027a8efff6c81104b55b550 to your computer and use it in GitHub Desktop.
Save brendonexus/11d241087027a8efff6c81104b55b550 to your computer and use it in GitHub Desktop.
Pagination that can be used on any website in bootstrap format
/**
* @param int $total Total number of records
* @param int $per_page How many records to display per page
* @param int $current_page Current page number
* @param string $link sprintf formatted string for page links $1 = page number
* @return string in html ul-li format
*/
function pagination($total, $per_page, $current_page, $link)
{
$boundry = 3; // How many pages to show around the current page
$current_page = (int)$current_page ? (int)$current_page : 1;
$html = '<ul class="pagination">';
$count_remainder = $total / $per_page;
$last = ceil($count_remainder);
if ($current_page > 1) {
$current_link = sprintf($link, $current_page - 1);
$html .= '<li class="page-item"><a class="page-link" href="' . $current_link . '">&lt;&lt; Prev</a></li>';
}
if ($last > 1) {
$has_gap = false;
for ($i = 1; $i <= $last; $i++) {
$show = false;
if ($current_page == $i) {
$sel = "active-pagination";
} else {
$sel = '';
}
if ($i == 1) {
$show = true;
}
if ($i > ($current_page - $boundry) && $i < ($current_page + $boundry)) {
$show = true;
}
if ($i == $last) {
$show = true;
}
if ($show == true) {
if ($has_gap == true) {
$html .= '<li class="page-item disabled"><a class="' . $sel . ' page-link">...</a></li>';
}
$has_gap = false;
$current_link = sprintf($link, $i);
$html .= '<li class="page-item'.($i==$current_page?' active':'').'"><a class="' . $sel . ' page-link" href="' . $current_link . '">' . $i . '</a></li>';
} else $has_gap = true;
}
}
if ($current_page != $last) {
$current_link = sprintf($link, $current_page + 1);
$html .= '<li class="page-item"><a class="page-link" href="' . $current_link . '">Next &gt;&gt;</a></li>';
}
$html .= '</ul>';
return $html;
}
echo pagination($total_items, 15, $current_page, 'list.php?p=%d');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment