views:

37

answers:

2

I've been doing some pagination recently and used the following:

if ( $totalPages > $pagesToShow ) {
    $start = $pageNumber - floor($pagesToShow/2);
    $end = $pageNumber + floor($pagesToShow/2);

    while ( $start < 1 ) {
        $start++;
        $end++;
    }

    while ( $end > $totalPages ) {
        $start--;
        $end--;
    }

} else {
    $start = 1;
    $end = $totalPages;
}

to work out where to start and end the list of surrounding pages. So that a paging list can be created like << < 1 2 3 4 5 > >>'.

Just wondering if there is a better method as using loops like that seems a little odd.

+1  A: 

You can replace the first loop

while ( $start < 1 ) {
    $start++;
    $end++;
}

with

if($start < 1)
{
    $end += (1 - $start);
    $start = 1;
}

Something similar can be done for the second loop, but the other way around:

if ( $end > $totalPages ) {
    $start -= ($end - $totalPages);
    $end = $totalPages;
}

Edit: It is much easier to just trim the page numbers which are out of bounds, replace your example code with:

$start = $pageNumber - $pagesToShow;
$end = $pageNumber + $pagesToShow;

if($start < 1)
    $start = 1;

if($end > $totalPages)
    $end = $totalPages;

$pagesToShow is the maximum amount of pages to show before and after the current page (if not out of bounds)

Veger
it works ok until you get to the penultimate page where it will only show one page either side of the current, or on the last page only show that one.
TonyVipros
You need to change `($totalPages - $end)` into `($end - $totalPages)` I guess... Since this results in a positive number (`$end` is bigger than `$totalPages`), this positive number can then be used to reduce `$start` to get some number in front of the current page number.
Veger
A: 

You might look in to using the Zend_Paginator control. It works with simple Arrays, as well as many other things. It will even handle giving you simple access to previous/next page information.

gms8994