This algorithm has the folowing features:
- To have a control on page numbers displayed. Total number of pages displayed will be an odd number i.e. 3, 5, 7, ....
- The first and last pages should be accessible on all pages
- To have equal number of page numbers on all pages, unless there are too few pages
Click Here to view an online demo of this algorigthm.
Have a look at the algorighth below. The variables used are explained below
- $grace is the number of pages on the left and right of current page, total number of page numbers displayed also depends on $grace. If $grace=5, total page numbers displayed will be 11 (like from 4 to 14).
- $start and $end are the starting and ending page numbers
- $current_page is current page number and $total_pages is the total number of pages
<?
/*
$current_page=$_REQUEST['page'];
$total_pages=120;
*/
$grace=5; // 5 pages on the left and 5 pages on the right of current page
$range=$grace*2;
$start = ($current_page - $grace) > 0 ? ($current_page - $grace) : 1;
$end=$start + $range;
if($end > $total_pages){ //make sure $end doesn't go beyond total pages
$end=$total_pages;
$start= ($end - $range) > 0 ? ($end - $range) : 1; //if there is a change in $end, adjust $start again
}
if($start>1){
echo "<a href='?page=1'>1</a> ...";
}
for($i=$start;$i<=$end;$i++){
if($i==$current_page){
echo "<span>$i</span> "; // Current page is not clickable and different from other pages
} else {
echo "<a href='?page=$i'>$i</a> ";
}
}
if($end < $total_pages){
echo "... <a href='?page=$total_pages'>$total_pages</a>"; // If $end is away from total pages, add a link of the last page
}
?>