Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

pagination

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.

like image 999
Michael Avatar asked Jan 30 '13 21:01

Michael


3 Answers

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);
like image 189
Veger Avatar answered Sep 22 '22 08:09

Veger


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

$currentpage = (($startIndex - 1) / $itemsPerPage) + 1;
like image 41
Sammitch Avatar answered Sep 26 '22 08:09

Sammitch


If:

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

then

$currentpage = $startIndex/$itemsPerPage; //Make sure that it uses integer division
like image 40
CoderOfHonor Avatar answered Sep 26 '22 08:09

CoderOfHonor