Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pagination, items per page dependant on number of results (PHP)

Tags:

php

pagination

long time lurker first time asker.

I'm trying to piece together a pagination function that will take into account the total amount of items and increase the results per page to ensure each page is fully populated.

For example if I had 35 results and I wanted a minimum of 10 results per page it would ideally return 12, 12 & 11 results per page.

Clearly my logic-fu is weak because I for the life of me cannot seem to comprehend this seemingly simple task. Embarrassing (it pains me to ask) as I've been at this for a week now and I know there's a simple answer to this.

I'm not necessarily asking for a solution (though that would be appreciated) as a hint in the right direction may be all I need.

like image 801
Jarf Avatar asked Dec 13 '25 19:12

Jarf


1 Answers

Supposing you have at least 10 items (test it) :

nbPages = floor(nbItems/10)

nbItemsPerPageMax = 10 + ceil((nbItems - 10*nbPages)/nbPages) 

You won't need to adjust for the last page as the limit clause don't need the exact number or items in this case (just use limit numPage*nbItemsPerPageMax, nbItemsPerPageMax).

like image 117
Denys Séguret Avatar answered Dec 15 '25 09:12

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!