codeguy
codeguy

Reputation: 700

PHP How to calculate the current display of paginated content

this should be really simple but I can just not figure it out at the moment - I have searched and can't find the right helping - maybe it's my wording of my problem which is the issue - I know this is simple but as I have said I am brain dead at the moment!

this is what I want Displaying 1 - 7 of 21 items

if there are 21 products in total with 7 per page it needs to say

1 - 7 of 21 on page one
8 - 14 of 21 on page two
15 - 21 of 21 on page three

pretty sure that is the right way to step up? anyway any help would be appreciated! and I can put a bounty on this - although small at least it's something! thanks

Upvotes: 0

Views: 2401

Answers (4)

nickb
nickb

Reputation: 59699

If you know what page you're on, and the number of entries per page, you can calculate it:

$limit = 7;
$page = 2;
$total = 21;

$upper = min( $total, $page * $limit);
$lower = ($page - 1) * $limit + 1;
printf( "Displaying %d - %d of %d on Page %d\n", $lower, $upper, $total, $page);

Now, just loop over pages 1 - 3 to see the outputCodepad:

Displaying 1 - 7 of 21 on Page 1
Displaying 8 - 14 of 21 on Page 2
Displaying 15 - 21 of 21 on Page 3

Edit: Using the OP's variables:

$upper = min( $products_total, $pager_current * $limit);
$lower = ($pager_current - 1) * $limit + 1;
printf( "Displaying %d - %d of %d on Page %d\n", $lower, $upper, $products_total, $pager_current);

Upvotes: 6

codeguy
codeguy

Reputation: 700

think this is working for me - seems to show the results I want no matter limit set

$display_end = ($pager_current * $limit);
$display_start = ($display_end - $limit) + 1;

if($pager_current == $pager_max){

$display_end = $products_total; //not great but works!

}

$displaying = 'Displaying '.$display_start.' - '.$display_end.' of '.$products_total.' items';

gives me the following output

Displaying 1 - 5 of 7 items
Displaying 6 - 7 of 7 items

when I have 7 total products and paginated at 5 per page or

Displaying 1 - 2 of 7 items
Displaying 3 - 4 of 7 items
Displaying 5 - 6 of 7 items
Displaying 7 - 7 of 7 items

when total products is 7 and paginated by 2 per page

Upvotes: 0

Mustafa
Mustafa

Reputation: 825

You know the Total Products you have:

$total=21;

You know the page you are on:

$cur_page=2;

You know the items on one page:

$itemcount=7;

Print that:

echo 'Displaying '.($itemcount*($cur_page-1)+1).' - '.$itemcount*$cur_page.' of '.$total.' items.';

Upvotes: 1

Marcus Recck
Marcus Recck

Reputation: 5065

$page = 0;
$max = 7;
$total = 21;

$totalPages = ceil($total / $max); // 3 pages
$currentRange = ($max*$page)+1 . " - " . ($max*($page+1));

echo $currentRange . " of " . $total;

I prefer starting $page at 0 and going up from there. It's pretty simple math.

Values of $currentRange up to 2 would be

1 - 7 of 21
8 - 14 of 21
15 - 21 of 21

Upvotes: 1

Related Questions