Skip to content

Instantly share code, notes, and snippets.

@mike183
Last active December 30, 2015 20:19
Show Gist options
  • Save mike183/7880282 to your computer and use it in GitHub Desktop.
Save mike183/7880282 to your computer and use it in GitHub Desktop.
A simple PHP function that can be used to generate pagination for use in a HTML template.
<?php
/**
* Generates an array of pages that could be used in an HTML template to
* create pagination links.
*
* @param integer $page
* @param integer $totalpages
* @param integer $spaces (change this value if you want to display more pages, this should be an odd number)
*
* @return array
*/
function pagination($page, $totalpages, $spaces = 5)
{
// Pagination
$pages = array();
// Calculate number of items required on each side of the current page
$sides = ($spaces - 1) / 2;
// Do we need to include some pages before the current page
if($totalpages > ($spaces+1)){
// Calculate pages before and after
$pagesbefore = $page - 1;
$pagesafter = $totalpages - $page;
// Is pagination weighted left?
if($pagesbefore < $sides && $pagesafter > $sides){
$ifrom = 1;
$ito = $spaces;
}
// Is pagination center weighted?
if($pagesbefore >= $sides && $pagesafter >= $sides){
$ifrom = $page - $sides;
$ito = $page + $sides;
}
// Is pagination weighted right?
if($pagesbefore > $sides && $pagesafter < $sides){
$ifrom = $totalpages - ($spaces-1);
$ito = $totalpages;
}
} else {
// Number of pages is less than or equal to the number of available
// spaces, we don't need to do anything
$ifrom = 1;
$ito = $totalpages;
}
// Generate pagination
for($i=$ifrom; $i<=$ito; $i++){
array_push($pages, $i);
}
// Create array to return
$data = array(
"currentpage" => $page,
"totalpages" => $totalpages,
"pagination" => $pages
);
// Return pagination
return $data;
}
?>

Usage Examples

Calling this:

$pagination = pagination(10, 30);

Returns this:

Array(
  "currentpage" => 10,
  "totalpages" => 30,
  "pagination" => Array(
    [0] => 8,
    [1] => 9,
    [2] => 10,
    [3] => 11,
    [4] => 12
  )
);

Calling this:

$pagination = pagination(33, 48, 11);

Returns this:

Array(
  "currentpage" => 33,
  "totalpages" => 48,
  "pagination" => Array(
    [0]  => 28,
    [1]  => 29,
    [2]  => 30,
    [3]  => 31,
    [4]  => 32,
    [5]  => 33,
    [6]  => 34,
    [7]  => 35,
    [8]  => 36,
    [9]  => 37,
    [10] => 38
  )
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment