I have a pagination script that displays a list of all pages like so:
prev [1][2][3][4][5][6][7][8][9][10][11][12][13][14] next
But I would like to only
$page = 3;
$totalPages = 33;
$count = 9;
$startPage = max(1, $page - $count);
$endPage = min( $totalPages, $page + $count);
if($page-1 > 0){
echo '<a class="btn btn-default" href="/search-results?page="'.($page-
1).'"><< Prev</a>';
}
for($i = $startPage; $i < $endPage; $i++): if($i <= $totalPages):
echo '<a class="btn btn-<?=$i == $page || $i == 1 && $page == "" ?
'success' : 'primary';?>"style="margin-right:2px;" href="/search-
results?page="'.$i.'">'.$i.'</a>';
endif; endfor;
if($page < $totalPages){
echo '<a class="btn btn-default" href="/search-results?page="'.
($page+1).'">Next >></a>';
}
10 next pages
for($i = $page + 1; $i <= min($page + 11, $total_pages); $i++)
or if you want 5 prev and 5 next
for($i = max(1, $page - 5); $i <= min($page + 5, $total_pages); $i++)
I've just been looking for an answer to the same original question, and couldn't find it, so this is what I came up with. I hope someone else finds it useful.
$totalPages = 20;
$currentPage = 1;
if ($totalPages <= 10) {
$start = 1;
$end = $totalPages;
} else {
$start = max(1, ($currentPage - 4));
$end = min($totalPages, ($currentPage + 5));
if ($start === 1) {
$end = 10;
} elseif ($end === $totalPages) {
$start = ($totalPages - 9);
}
}
for ($page = $start; $page <= $end; $page++) {
echo '[' . $page . ']';
}
Results:
$currentPage = 1; // [1][2][3][4][5][6][7][8][9][10]
$currentPage = 4; // [1][2][3][4][5][6][7][8][9][10]
$currentPage = 10; // [6][7][8][9][10][11][12][13][14][15]
$currentPage = 17; // [11][12][13][14][15][16][17][18][19][20]
$currentPage = 20; // [11][12][13][14][15][16][17][18][19][20]