What is the lowest and highest number of pagination

78 Views Asked by At

I am building a basic pagination bar to separate posts into pages. I have 3 numeric values:

$posts_per_page
$total_pages
$clicked_page_number

So for example, I have 31 posts. And my $posts_per_page value is 15, which means that $total_pages becomes 3.

My question is, how do I calculate the lowest and highest post number of the selected page?

To explain this, using the values above, if user clicks on page 2, then tghe lowest post number is 16 and the highest post number is 30.

1

There are 1 best solutions below

1
On

Let $p$ be the number of posts per page; $n_{\text{max}}$ the total number of posts and $n$ is the clicked page number.

When $n_{\text{max}} \leq p$, the analysis is easy: The first post is $1$ and the last one is $n_{\text{max}}$.

If $ n_{\text{max}} > p$, the posts will be distributed on different pages. In your example, the posts are distributed like so: $$ 31 = 15 + 15 + 1 $$ If there are many posts, how many are on the last page? The answer is the remainder of division between $n_{\text{max}}$ and $p$. Therefore, the post distribution in your example is $$ [1\dots 15],\quad [16\dots 30], \quad [31] $$ In general, we would have $$ [1, \dots p], \quad [p+1 \dots 2p], \quad [2p+1 \dots 3p], \quad \dots \quad ,[n_{\text{max}}-b,n_{\text{max}}-b + 1, \dots n_{\text{max}} ] $$ In this, I had to notate $b$ to be the remainder of the division. Usually, in programming, $$ b = MOD(n_{\text{max}}, p) $$ In practice you have to divide the analysis into the two cases like I did. Do you know how to do it now?