Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating item offset for pagination

Tags:

pagination

this seems like very simple maths but somehow, my brain cant think ...

i am trying to implement pagination and will need to calculate the item offset to use in limiting my result set. i am having problems calculating what index the first item of the page should have.

eg.

with 1 page having 10 items  page 1 will have items 1 - 10 page 2 ............... 11 - 20 page 3 ............... 21 - 30 

i thought of

offset = page * itemsPerPage + 1 

but this will not be the case for page 1. there must be a formula for this? am using PHP/Zend_Paginator/Doctrine2 but this should be language independent

wonder if this should be in the the maths stack exchange site

like image 959
Jiew Meng Avatar asked Aug 19 '10 10:08

Jiew Meng


People also ask

How is offset calculated in pagination?

Use offset = (page - 1) * itemsPerPage + 1 .

How is offset value calculated?

Find a value that, when subtracted from your augmented X value, leaves zero; this is the offset value for X coordinates. Db2 Spatial Extender subtracts this number from all X coordinates to produce only positive values. For example, if the augmented X value is -105, you need to subtract -105 from it to get 0.

What is offset and limit in API?

Offset & LimitThe maximum number of entries to return. If the value exceeds the maximum, then the maximum value will be used. The maximum offset for offset-based pagination is 300000 . Marker-based pagination is recommended when a higher offset is needed.


2 Answers

Use offset = (page - 1) * itemsPerPage + 1.

like image 165
Gumbo Avatar answered Sep 21 '22 11:09

Gumbo


Honestly depends. I'm no PHP person, but I'll put both out there. If you are pulling your records in to some form of collection (list, array, etc.) then your formula should be:

offset = (page - 1) * itemsPerPage 

This is because most (again, I'm not a PHP person) arrays and lists use 0 for their first element. If they do not use 0 for their first element and/or you're pulling from a table or something else where the IDs start at 1, then it should be:

offset = (page - 1) * itemsPerPage + 1 

I hope that's clear and helps.

like image 22
XstreamINsanity Avatar answered Sep 19 '22 11:09

XstreamINsanity