Skip to content
PHP Logo

How can the pagination script be optimized to display only the next 5 pages and replace the rest with "..."?

To optimize the pagination script to display only the next 5 pages and replace the rest with "..." we can modify the logic in the pagination script to dynamically generate the page links based on the current page. This can be achieved by calculating the start and end page numbers to display and replacing the rest with "..." when there are more than 5 pages.

php
<?php
$current_page = 1; // Current page number
$total_pages = 20; // Total number of pages

$start_page = max($current_page - 2, 1);
$end_page = min($start_page + 4, $total_pages);

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

for ($i = $start_page; $i <= $end_page; $i++) {
    echo '<a href="?page=' . $i . '">' . $i . '</a>';
}

if ($end_page < $total_pages) {
    if ($end_page < $total_pages - 1) {
        echo '...';
    }
    echo '<a href="?page=' . $total_pages . '">' . $total_pages . '</a>';
}
?>