In PHP, how do I paginate arrays with SPL?

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> "; } ?>

PHP Pagination SPL ArrayObject Example