How to paginate an array
Short answer
array_slice() takes the needed portion: the offset is the page number minus one, multiplied by the page size:
<?php
$items = range(1, 23);
$page = 3;
$perPage = 5;
echo implode(', ', array_slice($items, ($page - 1) * $perPage, $perPage));Output:
11, 12, 13, 14, 15How many pages in total
Divide the count by the page size and round up:
<?php
$items = range(1, 23);
echo (int) ceil(count($items) / 5);Output:
5Data from a database
Only small arrays are paginated this way. Database records are cut by the query itself — LIMIT and OFFSET — so the whole table is not loaded into memory.
Functions used in this recipe
- array_slice — Returns part of an array.
- ceil — Rounds a number up to an integer.
- count — Returns the number of elements in an array.