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>
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.