PHP


The PHP Paging Algorithm
By Richard Clark
17-Jan-10
Views: 951

There is already an article on Partitioning Results into Pages on QualityCodes, Here is an improved version of paging algorithm.
 
Features (Page 1 of 1)

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>&nbsp;&nbsp;";		// Current page is not clickable and different from other pages
		} else {
			echo "<a href='?page=$i'>$i</a>&nbsp;&nbsp;";
		}
	}
	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
	}
 ?>
Comments
josesoal
[24-May-2010]
#1

Nicer!!. Your code is very clean. I'll use it now. Thanks. Give us your mail for asking you more tips about php.

Broseph
[10-Jun-2010]
#2

This is by far the best code on the interwebs.

Small and very easy to implement! Thanks a gazillion.

Leave a Comment
Age (Required, will not be shown)
Name
Email (Required, will not be shown)
Website (Optional, starting with http://)
 
Are you human ?

Enter the code shown above