How can PHP developers optimize the display of page numbers in pagination to ensure readability and user experience?

When displaying page numbers in pagination, PHP developers can optimize readability and user experience by limiting the number of visible page links shown to users. This can be achieved by only displaying a subset of total page numbers, such as the current page, a few pages before and after, and the first and last pages. This approach prevents overwhelming users with too many page links and improves navigation clarity.

// Function to generate pagination links with optimized display of page numbers
function generatePaginationLinks($totalPages, $currentPage) {
    $maxVisiblePages = 5; // Define the maximum number of visible page links
    $startPage = max(1, $currentPage - 2);
    $endPage = min($totalPages, $startPage + $maxVisiblePages - 1);

    // Display first page link
    if ($startPage > 1) {
        echo '<a href="?page=1">1</a>';
        if ($startPage > 2) {
            echo '...';
        }
    }

    // Display page links within the range
    for ($i = $startPage; $i <= $endPage; $i++) {
        echo '<a href="?page=' . $i . '">' . $i . '</a>';
    }

    // Display last page link
    if ($endPage < $totalPages) {
        if ($endPage < $totalPages - 1) {
            echo '...';
        }
        echo '<a href="?page=' . $totalPages . '">' . $totalPages . '</a>';
    }
}

// Example usage
$totalPages = 20;
$currentPage = 5;
generatePaginationLinks($totalPages, $currentPage);