views:

27

answers:

0
function paginator($totalPages,$currentPage)
{
    if($currentPage > $totalPages)
     return false;
    $aheadmin = max(1,$currentPage - ($totalPages - $currentPage > 3 ? 2 : (5 - ($totalPages - $currentPage) -1)));

    if($aheadmin - 1 > 1)
    {
     $str = '1 ... ';
     $aftermax = min($currentPage + 2,$totalPages);
    }
    else if($aheadmin - 1 > 0)
    {
     $str = '1 ';
     $aftermax = min($currentPage + 1,$totalPages);
    }
    else
    {
     $str = '';
     $aftermax = min(5,$totalPages);
    }

    for($i = $aheadmin; $i <= $aftermax; $i++)
    {
     $str .= $i . ' ';
    }

    if($totalPages - $aftermax > 1)
     $str .= '.. ' . $totalPages;
    else if($totalPages - $aftermax > 0)
     $str .= $totalPages;
    return $str;
}

echo 'Total Pages:';
$total = trim(fgets(STDIN));
while(true)
{
    echo 'CurrentPage:';
    $current = trim(fgets(STDIN));
    echo paginator($total,$current) . "\r\n";
}

Which output something like:

Total Pages:100
CurrentPage:97
1 ... 96 97 98 99 100
CurrentPage:95
1 ... 93 94 95 96 97 .. 100
CurrentPage:96
1 ... 94 95 96 97 98 .. 100
CurrentPage:99
1 ... 96 97 98 99 100
CurrentPage:1
1 2 3 4 5 .. 100
CurrentPage:2
1 2 3 4 5 .. 100
CurrentPage:3
1 2 3 4 5 .. 100
CurrentPage:4
1 2 3 4 5 .. 100
CurrentPage:5
1 ... 3 4 5 6 7 .. 100