PHP
Manually Paginate a Simple PHP Array
Implement manual pagination for any PHP array to display a subset of its elements per page, useful for non-database driven lists or search results.
<?php
function paginateArray(array $array, int $page = 1, int $perPage = 10): array {
$totalItems = count($array);
$totalPages = (int) ceil($totalItems / $perPage);
$offset = ($page - 1) * $perPage;
// Ensure page is within valid range
$page = max(1, min($page, $totalPages));
return array_slice($array, $offset, $perPage);
}
$allProducts = [];
for ($i = 1; $i <= 50; $i++) {
$allProducts[] = "Product " . $i;
}
$currentPage = 2;
$itemsPerPage = 10;
$paginatedProducts = paginateArray($allProducts, $currentPage, $itemsPerPage);
echo "--- Page $currentPage ---
";
print_r($paginatedProducts);
// Expected Output (for currentPage=2, itemsPerPage=10):
// --- Page 2 ---
// Array
// (
// [0] => Product 11
// [1] => Product 12
// [2] => Product 13
// [3] => Product 14
// [4] => Product 15
// [5] => Product 16
// [6] => Product 17
// [7] => Product 18
// [8] => Product 19
// [9] => Product 20
// )
?>
How it works: The `paginateArray` function takes a source array, current page number, and items per page. It calculates the total number of pages and the offset, then uses `array_slice` to extract only the relevant items for the requested page. This is a robust way to implement pagination when data is already loaded into a PHP array, without relying on database-specific solutions.