What are the best practices for implementing pagination in PHP when retrieving data from an array?

When implementing pagination in PHP for retrieving data from an array, it is important to limit the number of items displayed on each page and calculate the offset for fetching the correct subset of data. This can be achieved by using array slicing functions like array_slice() to extract the desired portion of the array based on the current page number and items per page.

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

// Pagination parameters
$itemsPerPage = 10;
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$offset = ($page - 1) * $itemsPerPage;

// Get subset of data for current page
$currentPageData = array_slice($data, $offset, $itemsPerPage);

// Display data
foreach ($currentPageData as $item) {
    echo $item . "<br>";
}

// Pagination links
$totalPages = ceil(count($data) / $itemsPerPage);
for ($i = 1; $i <= $totalPages; $i++) {
    echo "<a href='?page=$i'>$i</a> ";
}