Skip to content

Instantly share code, notes, and snippets.

@LaffinToo
Created December 31, 2011 18:44
Show Gist options
  • Save LaffinToo/1544915 to your computer and use it in GitHub Desktop.
Save LaffinToo/1544915 to your computer and use it in GitHub Desktop.
Pagination calculation routine #paginate #pagination
<?php
/* Wrote this for a pagination routine awhile back
the variables needed
$range = Amount of numbers to display
$curpage = Current number
$pages = Highest Page count
*/
$midrange=intval(floor($range/2));
$range_s=(($curpage-$midrange)<1?1:(($curpage+$midrange)>$pages?($pages-$range+1):$curpage-$midrange));
$range_e=(($curpage+$midrange)>$pages?$pages:($curpage-$midrange<1?($range):$curpage+$midrange));
// I love the trenary operator keeps me from using a bunch of if...elseif..else statements
$midrange=intval(floor($range/2)); // find the middle of the range
// FInd the starting range
if(($curpage-$midrange)<1) // If we subtract midrange from the current page, is it below page 1?
$range_s=1; // Yes, well put the start at page 1 then
elseif(($curpage+$midrange)>$pages) // No, Well than If we add the midrange to the current page, are we above the highest page?
$range_s=($pages-$range+1) // Yes, well start at the lowest possible range than
else $range_s=$curpage-$midrange; // No, than go ahead subtract midrange from the current page
// find the ending range
if(($curpage+$midrange)>$pages) // If we add the current page to our midrange, are we above the page count?
$range_e=$pages; // Yes, Well use the page count
elseif(($curpage-$midrange<1) // No, Well than does the Lowest page invalid?
$range_e=$range; // Yes, Well than use the Range instead of calculating
else $range_e=$curpage+$midrange; // No, than go ahead add midrange to the current page
@baris1892
Copy link

baris1892 commented May 20, 2018

Even if this is quite old, it works pretty well, but I would add the following to the end to check that the result is between 1 and $pages. Currently it is possible that $range_s is contains negative values.

     $range_s = max($range_s, 1);
     $range_e = min($range_e, $pages);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment