NewbieLearner
NewbieLearner

Reputation: 85

Next, Prev and the numbers inbetween

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.

This is what I get

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 :)

enter image description here

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 .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
} else if ($pn == $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
}

Upvotes: 0

Views: 48

Answers (1)

Rick James
Rick James

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

Related Questions