In PHP, how do I paginate arrays in vanilla PHP?

PHP, Pagination, Arrays
This example demonstrates how to paginate an array in vanilla PHP for managing large datasets efficiently.
<?php function paginateArray($array, $currentPage, $itemsPerPage) { $totalItems = count($array); $totalPages = ceil($totalItems / $itemsPerPage); // Ensure current page is within bounds if ($currentPage < 1) $currentPage = 1; if ($currentPage > $totalPages) $currentPage = $totalPages; $startIndex = ($currentPage - 1) * $itemsPerPage; return array_slice($array, $startIndex, $itemsPerPage); } // Example usage $data = range(1, 100); // An array of numbers from 1 to 100 $currentPage = 2; // Current page number $itemsPerPage = 10; // Number of items per page $paginatedData = paginateArray($data, $currentPage, $itemsPerPage); print_r($paginatedData); ?>

PHP Pagination Arrays