Skip to content

Instantly share code, notes, and snippets.

@zikes
Created October 8, 2012 17:24
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 zikes/3853729 to your computer and use it in GitHub Desktop.
Save zikes/3853729 to your computer and use it in GitHub Desktop.
PHP Pagination
<?php
// global configuration,
$page_size = 5; // how many items per page
$page_start = 1; // the starting page
// how many numbers will be shown before and after current, including current
$page_range_near = 3;
// The number of items to paginate through, most likely the result of
// a "SELECT COUNT(*)" query.
$item_count = 1000;
// Divide the number of items by the page size and round up to the nearest
// integer.
$num_pages = ceil($item_count / $page_size);
$current_page = 25; // what page you're on right now
// grab the current page if specified in the URL
if(isset($_GET['page'])){
$current_page = (int) $_GET['page'];
}
function pagination($start, $num_pages, $current, $near = 3){
// True if the for loop is within a range of hidden numbers, represented
// by an ellipsis.
$hidden_range = false;
// $out: output string. Would probably be better served by an array
// that you push your output into, then join and return at the
// end, but at this point that's premature optimization
$out = "<ul class=\"pagination\">";
for($pg = $start; $pg <= $num_pages; $pg++){
if(
// Always show the number for the first page.
$pg == $start
||
// Always show the number for the last page.
$pg == $num_pages
||
// Show the number for the current page.
$pg == $current
||
// Show the number if it's within $near of current page
(
$pg > $current - $near
&&
$pg < $current + $near
)
){
// Output page number
if($pg == $current){
$out.="<li><a href='/pager.php?page=$pg'><strong>$pg</strong></a></li>";
}else{
$out.="<li><a href='/pager.php?page=$pg'>$pg</a></li>";
}
$hidden_range = false;
}else{
if(!$hidden_range){
$out.="<li>...</li>";
$hidden_range = true;
}
}
}
$out.= "</ul>";
return $out;
}
?>
<?php echo pagination($page_start, $num_pages, $current_page, $page_range_near); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment