How to limit the number of pages displayed on a page?


With this question that already has a workaround, I got as a result a paginação com PDO but I have one more problem that will possibly be the target of a reward next week.

As you can see in the image below, I have this page with +/- 1000 properties that divided by groups of 12 per page, will return me a total of +/- 90 pages that will be written in the form of pagination causing me to have a 3 or 4 lines showing numbers that will lose meaning and will be monstrously horrible.

HowcanIlimitthenumberofpagestobeshownbyreusingthecodedisplayedwithin answered question in this one? If you find it necessary, I'll replicate the code here that is here .

asked by anonymous 03.10.2014 / 22:03

1 answer


It's easy to do this.

First set a boundary of links to be displayed before and after:

$lim = 3;

Then set the start of the display to the current page and limit:

$inicio = ((($pg - $lim) > 1) ? $pg - $lim : 1);

If subtraction is greater than 1, start with it, if not from 1.

Then set the final limit:

$fim = ((($pg+$lim) < $qtdPag) ? $pg+$lim : $qtdPag);

If the sum is less than the final quantity, then end with it, if not the final quantity.

And finally, define loop by starting and ending these rules:

if($qtdPag > 1 && $pg <= $qtdPag){
   for($i = $inicio; $i <= $fim; $i++){

      if($i == $pg){
         echo "<li><a class='ativo'>".$i."</a></li>";
      } else {
        echo "<li><a href='busca?pg=$i'>".$i."</a></li>";


If the user is on page 5, the links that will be displayed are:

[2] [3] [4] 5 [6] [7] [8]
03.10.2014 / 22:29