In PHP, how do I paginate objects in a memory-efficient way?

Pagination is a technique used to divide a large set of data into smaller, more manageable parts or "pages." This is especially important when dealing with large objects in PHP, as it helps to maintain memory efficiency and improves user experience by reducing load times.

Here's an example of how to paginate an array of objects in PHP in a memory-efficient way:

<?php // Sample data: an array of objects $items = array(); for ($i = 1; $i <= 100; $i++) { $items[] = (object) ['id' => $i, 'name' => 'Item ' . $i]; } // Pagination settings $itemsPerPage = 10; // Number of items per page $totalItems = count($items); // Total number of items $totalPages = ceil($totalItems / $itemsPerPage); // Total number of pages // Get the current page from the URL (default is 1) $currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1; // Validate page number if ($currentPage < 1) $currentPage = 1; if ($currentPage > $totalPages) $currentPage = $totalPages; // Calculate the offset for the SQL query $offset = ($currentPage - 1) * $itemsPerPage; // Fetch only the required items for the current page $pagedItems = array_slice($items, $offset, $itemsPerPage); // Display items foreach ($pagedItems as $item) { echo "<div>" . $item->name . "</div>"; } // Pagination controls for ($i = 1; $i <= $totalPages; $i++) { echo "<a href='?page=" . $i . "'>" . $i . "</a> "; } ?>

Pagination PHP Memory-efficient Objects Array Slicing Web Development