Michael
Michael

Reputation: 833

How to get current page using start index, items per page, total items, and total pages? (PHP)

For example, let's say:

$startIndex = 21; 
$totalItems = 100;
$itemsPerPage = 10;
$totalPages = ceil($totalItems / $itemsPerPage);  // (10)

$currentpage = //I am stumped here.

What would $currentpage be, based on $startIndex?

I'm working on pagination and it's kicking my butt. I know it's probably some very simple math, but I can't think right now.

Upvotes: 11

Views: 29625

Answers (4)

472084
472084

Reputation: 17885

It's important to use floor to get current page

pagesTotal = int(ceil(count / limit))
pagesCurrent = int(floor(offset / limit) + 1)

Upvotes: 0

Veger
Veger

Reputation: 37905

With 10 items per page and assuming your item count/numbering starts at 1, page 1 contains items 1 to 10, page 2 contains items 11 to 20, page 3 contains 21 to 30, and so on.

So,

$currentPage = ceil(($startIndex - 1) / $itemsPerPage) + 1;

I used ceil() to make sure you have an integer number, which is rounded up so the current page number is correct.


If your item count starts at 0, so page 1 contains items 0 to 9, you can skip the - 1 and + 1 parts of the formula:

$currentPage = ceil(($startIndex) / $itemsPerPage);

Upvotes: 22

CoderOfHonor
CoderOfHonor

Reputation: 741

If:

$startIndex = 21; 
$totalItems = 100;
$itemsPerPage = 10;
$totalPages = ($totalItems / $itemsPerPage);  // (10)

then

$currentpage = $startIndex/$itemsPerPage; //Make sure that it uses integer division

Upvotes: 1

Sammitch
Sammitch

Reputation: 32242

You slept a lot in math class, didn't you?

$currentpage = (($startIndex - 1) / $itemsPerPage) + 1;

Upvotes: 10

Related Questions