In PHP, how do I paginate arrays for beginners?

Pagination is a technique used to divide a large dataset into smaller chunks, so it can be navigated easily. In PHP, you can paginate arrays using a combination of functions like `array_slice` along with pagination controls like "Next" and "Previous". This example illustrates how to paginate an array of items.

<?php // Sample array of items $items = range(1, 100); // Array of numbers 1 to 100 $itemsPerPage = 10; // Define how many items per page $currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1; // Get current page from URL, default to 1 // Calculate total pages $totalItems = count($items); $totalPages = ceil($totalItems / $itemsPerPage); // Calculate the start and end index for the slice $startIndex = ($currentPage - 1) * $itemsPerPage; $pagedItems = array_slice($items, $startIndex, $itemsPerPage); // Get the items for the current page // Output the paginated items echo '<ul>'; foreach ($pagedItems as $item) { echo '<li>' . $item . '</li>'; } echo '</ul>'; // Pagination controls if ($currentPage > 1) { echo '<a href="?page=' . ($currentPage - 1) . '">Previous</a> '; } if ($currentPage < $totalPages) { echo '<a href="?page=' . ($currentPage + 1) . '">Next</a> '; } ?>

PHP pagination arrays array_slice HTML coding tutorial