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

Michael picture Michael · Jan 30, 2013 · Viewed 16.1k times · Source

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.

Answer

Veger picture Veger · Jan 30, 2013

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);