With a slight rephrase, the rules you mentioned become easier to understand.
The following ruleset is equivalent:
Any page number that is either the
first,
second,
second before current,
first before current,
current,
first after current,
second after current,
second to last,
or last page
should be displayed. Any other page should be an ellipsis.
Worked out in code, this becomes:
//Note: I'm addressing the pages as a 1-based index.
//If 0-based is needed, just add -1 to all index values
bool previousPageIsEllipsis = false;
for(int i = 1; i <= totalpages; i++)
{
if(i == currentpage) {
//Print current page number
previousPageIsEllipsis = false;
}
else
{
if( i == 1
|| i == 2
|| i == currentpage - 2
|| i == currentpage - 1
|| i == currentpage + 1
|| i == currentpage + 2
|| i == totalpages - 1
|| i == totalpages)
{
//Print a visible link button
previousPageIsEllipsis = false;
}
else
{
if(previousPageIsEllipsis)
{
//an ellipsis was already added. Do not add it again. Do nothing.
continue;
}
else
{
//Print an ellipsis
previousPageIsEllipsis = true;
}
}
}
}
I did not add the actual code, because you have that already. But here, you see there are three options: either show the page, show an ellipsis, or show nothing new if the previous element is already an ellipsis.
Just insert the needed HTML output on the //comment lines
and you should be good to go :)
Note: I made a 4th option (for the current page), because you generally want to render that as a non-clickable item.