What are the best practices for pagination in PHP when dealing with arrays?

When dealing with arrays in PHP and implementing pagination, it is important to consider the total number of items in the array, the number of items to display per page, and the current page number. By properly calculating the offset and limit for each page, you can efficiently display the desired subset of items without loading the entire array into memory.

// Sample array of items
$items = range(1, 100);

// Pagination variables
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$limit = 10;
$totalItems = count($items);
$totalPages = ceil($totalItems / $limit);
$offset = ($page - 1) * $limit;

// Display items for current page
$currentPageItems = array_slice($items, $offset, $limit);

// Display pagination links
for ($i = 1; $i <= $totalPages; $i++) {
    echo "<a href='?page=$i'>$i</a> ";
}

// Display current page items
foreach ($currentPageItems as $item) {
    echo $item . "<br>";
}