0

So i have my pagination links like this.

for ( $counter = 0; $counter <= $page_amount; $counter += 1) {
        echo "<a href=\"section.php?q=$section&p=$counter\">";
        echo $counter+1;
        echo "</a>";
     }

And the links grows like:

1 2 3 4 5 6 7 and so on.

But i want to limit this so if there is more than 7 pages it shall only show 7 links like this:

1 2 3 ... 10 11 12

where 12 is the last page.

And if you go to next page it will only change the first pages like this:

3 4 5 ... 10 11 12

until you reach the last 7 pages like this:

6 7 8 9 10 11 12

How do i do this ??

please help.

  • 4
    [What have you tried?](http://www.whathaveyoutried.com/) See [ask advice](http://stackoverflow.com/questions/ask-advice), please. – John Conde Feb 07 '13 at 01:19
  • first time i visit this website and i get this much help =/ yay! i guess it was a onetimetry then.. – user2049048 Feb 07 '13 at 01:22
  • if you expect help with out showing any attempt to fix it your self, then yes visit else where. –  Feb 07 '13 at 01:31
  • my attempt is right above thats as far as iv gotten... – user2049048 Feb 07 '13 at 01:32
  • `if ($counter >7){//something}` –  Feb 07 '13 at 01:40
  • 1
    use some mathematics to make a general equation and then code it with simple if statement & loop – Seder Feb 07 '13 at 01:44
  • The link provided in the accepted answer of http://stackoverflow.com/questions/163809/smart-pagination-algorithm would be a good place to start (not exactly what you want, but pretty close) – tmuguet Feb 07 '13 at 01:52

1 Answers1

0

Here is one way to do it.

// Set some presets
$current_page = 0;
$page_amount = 11;
$limiter = 7;

// Set upper and lower number of links
$sides = round(($limiter/2), 0, PHP_ROUND_HALF_DOWN);

for ( $counter = 0; $counter <= $page_amount; $counter++) {
    // Start with Current Page
    if($counter >= ($current_page)){
        // Show page links of upper and lower
        if(($counter <($current_page+$sides))||($counter >($page_amount-$sides))){
            echo "<a href=\"section.php?q=$section&p=$counter\">";
            echo $counter+1;
            echo "</a> ";
        }
        // The middle link
        elseif($counter ==($current_page+$sides)){
            echo "<a href=\"page.php?p=$counter\">";
                    // Show number if number of links == $limiter
            if(($page_amount-$current_page)==$limiter-1){
                 echo $counter+1;
            }
            // Show '...' number of links > $limiter 
                    else {
                     echo "...";
            }
            echo "</a> ";
        }
     }
}

This allows to change the number of links shown, ie. from 7 to 9.

Note, using PHP_ROUND_HALF_DOWN in round() requires php>=5.3

Sean
  • 12,443
  • 3
  • 29
  • 47