0

The previous next links are working with the code below. However, when I get to the start or end of the array, my links produce an UNDEFINED OFFSET error. I have tried placing isset() but I don't get how to use it to stop at the start or end. I tried using an if / else if to measure the total array against the current page, but can't figure it out. Any help is greatly appreciate. Thank you.

<?php

$currentPage = array_search(current((object) array($keyword)), array_column($totalNodes, 'keyword'));

echo '<p>Current Page: ' . $currentPage . '</p>';

$nextPage = $totalNodes[$currentPage - 1]->keyword . PHP_EOL;
$nextTitle = $totalNodes[$currentPage - 1]->title . PHP_EOL;

$prevPage = $totalNodes[$currentPage + 1]->keyword . PHP_EOL;
$prevTitle = $totalNodes[$currentPage + 1]->title . PHP_EOL;

?>

<p>
<a href="/blog/<?= $nextPage ?>">Next</a>
   <a href="/blog/<?= $nextPage ?>"><?= $nextTitle ?></a>
</p>

<p>
   <a href="/blog/<?= $prevPage ?>">Prev</a>
   <a href="/blog/<?= $prevPage ?>"><?= $prevTitle ?></a>
</p>

2 Answers2

0

If the problem is that you are accessing a position that does not exist you could try array_key_exists():

if (array_key_exists($currentPage - 1, $totalNodes)) {
    // the previous index exist
}

if (array_key_exists($currentPage + 1, $totalNodes)) {
    // the next index exist
}

There is a similar question here.

Forbrig
  • 36
  • 6
0

This worked!

if (array_key_exists($currentPage + 1, $totalNodes)) {
   $prevPage = $totalNodes[$currentPage + 1]->keyword . PHP_EOL;
   $prevTitle = $totalNodes[$currentPage + 1]->title . PHP_EOL;
}

if (array_key_exists($currentPage - 1, $totalNodes)) {
   $nextPage = $totalNodes[$currentPage - 1]->keyword . PHP_EOL;
   $nextTitle = $totalNodes[$currentPage - 1]->title . PHP_EOL;
}

// and then added this for the links

if (isset($prevPage)) {
// if $prevPage is set, show the link
echo '<a href="/blog/' . $prevPage . '">&larr; Prev: ' . $prevTitle . '</a>';
}

if (isset($nextPage)) {
//// $nextPage is set, show the link
   echo '<a href="/blog/' . $nextPage . '">Next: ' . $nextTitle . ' &rarr;</a>';

}