In what ways can PHP developers optimize the generation of pagination numbers based on a given total page count to improve performance and user experience?

When generating pagination numbers based on a total page count in PHP, developers can optimize performance and user experience by limiting the number of displayed page numbers to a manageable range, such as showing only a subset of pages at a time. This can prevent overwhelming users with a long list of page numbers and improve the speed of rendering the pagination interface.

<?php
function generatePagination($totalPages, $currentPage, $perPage = 10) {
    $pagination = [];
    
    $start = max(1, $currentPage - 2);
    $end = min($totalPages, $start + $perPage - 1);
    
    for ($i = $start; $i <= $end; $i++) {
        $pagination[] = $i;
    }
    
    return $pagination;
}

$totalPages = 20;
$currentPage = 5;
$pagination = generatePagination($totalPages, $currentPage);

foreach ($pagination as $page) {
    echo "<a href='?page=$page'>$page</a> ";
}
?>