Saturday, October 24, 2009

Pagination pagelinks PHP algorithm

If you are making a pagination with adjacent links and are trying to figure out how to find out which number the links should start at, the algorithm below should help.

Case 1
Not enough pages, just show them all..
if (totalPages < adjacent*2)
[1]-2-3-4

Case 2
Almost at start, just start showing from beginning
true when currentPage - adjacent < 1
1-[2]-3-4-5-6 ..
starti = 1

Case 3
Almost reached the end, start showing till reached end
true when currentPage + adjacent > totalPages-1
.. 6-7-8-9-[10]-11
starti = currentPage-adjacent*2+(totalPages-currentPage)

Case 4
Not close to end or start, show even number of adjacent links on each side
true when none of above cases match
.. 2-3-[4]-5-6 ..
starti = currentPage-adjacent;


if ($this->totalPages <= $this->adjacent*2) {
$starti = 1;
$endi = $this->totalPages;
}
else if ($this->currentPage - $this->adjacent < 1) {
$starti = 1;
$endi = $this->adjacent*2;
}
else if ($this->currentPage + $this->adjacent > $this->totalPages-1) {
$starti = $this->currentPage - $this->adjacent*2 + ($this->totalPages-$this->currentPage);
$endi = $this->totalPages;
}
else {
$starti = $this->currentPage - $this->adjacent;
$endi = $this->currentPage + $this->adjacent;
}

No comments: