Reputation: 85
Hey so I tried tweaking this code I got from stackoverflow, I searched and searched and found the video which explained it and I was able to "tweak" it more but I don't understand it and As shown in image when I try to make it display more adjacent numbers, it shows -1, -2 or 50, 51 when I only got 49 pages.
I'm trying to make it display 4 adjacent numbers as shown in image below. I really can't wrap my head around the code. I altered if and all else if as well as only one at a time and still no luck. Any inputs are welcome :)
Below is the unaltered code, I added variables $sub3,4,5.. and $add3,4,5... and that's the result the image is of. Plenty of posts have this code in it so I don't know who the original code is from... Source?
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
} else if ($pn == $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> ';
} else if ($pn > 1 && $pn < $lastPage) {
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> ';
$centerPages .= ' <span class="pagNumActive">' . $pn . '</span> ';
$centerPages .= ' <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> ';
}
Upvotes: 0
Views: 48
Reputation: 142298
Ok if I simplify the task rather than figure out your bug? Assuming $pn is the current page and $last=49 (in your example):
$start = max(1, $pn - 4); // don't want negative or zero
$end = min($pn + 4, $last); // don't want to go past 49
foreach($range($start, $end) as $n)
{
if ($n == $pn) ... not linked ... else ... linked ...
}
Upvotes: 1