Posted By

iroybot on 02/10/09


Tagged

pagination Paginierung


Versions (?)

Who likes this?

7 people have marked this snippet as a favorite

cessnajumpin
PapTom
lfatr
pezland
vali29
iroybot
nerdfiles


Pagination Madness


 / Published in: PHP
 

  1. // pagination
  2. $itemcount = $res->length();
  3. $pagemin = ($itemcount / 4);
  4. $pagemax = (($itemcount / 4) + .499);
  5. $roundmax = round($pagemax);
  6. $roundmin = round($pagemin);
  7. if ( (intval($roundmax) - intval($roundmin) === 1) ) {
  8. $pages = intval($roundmax);
  9. } else {
  10. $pages = intval($roundmin);
  11. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: iroybot on February 20, 2009

Let's say we want to show 4 items per page. Let's calculate this through:

first case: we have 8 items. 8 divided by 4 is 2 so we need two pages. good

second case: we have 9 items. 9 divided by 4 gives us 2.25.

So we clearly need a 3rd page here. That's why I compare two values here: the actual division result and one with an extra 0.499 added what gives us 2.749. (lines 2-4) lines 5-6 we round both results in order to find out if they get rounded to different integers. if they differ by 1 we have a scenario where we want another page, so we pick the bigger result as our page number. (lines 7-8). if they get rounded to the same integer we are happy and use the smaller number.

note: if we added 0.5 instead of 0.499 the first case would give us 2.5 which would have been rounded to 3. but actually we are fine with 2 pages for 8 items.

now that we know our actual page count we can do something like

while($i = 1;$i <= $pages; $i++) { print '<a href="?page=' . $i . '">'; }

Posted By: iroybot on April 24, 2009

shame on me... use PHPs native ceil() function (instead of this crazy +.499 guessing, I did...)

You need to login to post a comment.