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> ";
}
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?