This example demonstrates how to paginate an array using SPL in PHP.
PHP, Pagination, SPL, ArrayObject, Example
This PHP code snippet shows how to efficiently paginate an array of data using SPL functionalities.
<?php
// Initialize an array
$data = range(1, 100); // An example array with 100 items
// Pagination parameters
$itemsPerPage = 10; // Number of items per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1; // Current page or default to 1
// Calculate total pages
$totalItems = count($data);
$totalPages = ceil($totalItems / $itemsPerPage);
// Create an SPL ArrayObject
$arrayObject = new ArrayObject($data);
// Get the items for the current page
$offset = ($page - 1) * $itemsPerPage;
$itemsToDisplay = array_slice($arrayObject->getArrayCopy(), $offset, $itemsPerPage);
// Output the current page items
foreach ($itemsToDisplay as $item) {
echo $item . "<br>";
}
// Create pagination links
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?