Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

paging like stackoverflow's

i'm a newbie in php especially on making pagination.

my question is, how to make paging like stackoverflow's pagination?
i mean paging like this :

1 ... 5 6 7 8 9 ... 25
(the first number and the last number is always appear, but in the middle only 5 numbers with the selected page absolutely in the middle)

in php i have tried making paging,

<?php

//Show page links
for($i=1; $i<=$pages; $i++)
{
    echo '<li id="'.$i.'">'.$i.'</li>';
}

?>

but it will be shown all of pages like

1 2 3 4 5 6 7 8 9 10 etc

any body have simple logic example to solve this problem?
many thanks :)

like image 586
bungdito Avatar asked Jun 30 '26 08:06

bungdito


1 Answers

This will generate the numbers as per above with current = 7, pages = 25. Replace the numbers with links to get an actual pagination index.

$current = 7;
$pages = 25;
$links = array();

if ($pages > 3) {
    // this specifies the range of pages we want to show in the middle
    $min = max($current - 2, 2);
    $max = min($current + 2, $pages-1);

    // we always show the first page
    $links[] = "1";

    // we're more than one space away from the beginning, so we need a separator
    if ($min > 2) {
        $links[] = "...";
    }

    // generate the middle numbers
    for ($i=$min; $i<$max+1; $i++) {
        $links[] = "$i";
    }

    // we're more than one space away from the end, so we need a separator
    if ($max < $pages-1) {
        $links[] = "...";
    }
    // we always show the last page
    $links[] = "$pages";
} else {
    // we must special-case three or less, because the above logic won't work
    $links = array("1", "2", "3");
}
echo implode(" ", $links);

Output:

1 ... 5 6 7 8 9 ... 25
like image 92
lunixbochs Avatar answered Jul 02 '26 21:07

lunixbochs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!