2

I have an array of blog_ids and i want to navigate to the previous and next blog_id in that array.

foreach($blog_ids as $blog_id) {
    echo $blog_id.'<br />';
}
// output:
id_20200523214047
id_20200523003107
id_20200521125410
id_20200521123813
id_20200514222532

From the current page, i grab the id with $_GET['page'];

echo $_GET['page'];
// ouput
id_20200521125410 (3rd value of array)

How can i now navigate to the previous and next value in that array, from the current id i am? Previous should be: id_20200523003107 and next should be id_20200521123813

1
  • The array has numeric indices? Also could id also be first, or last record? Likely you're better off to query for the other two ids. Not sure how $blog_ids gets built but that likely could be inefficient. Commented May 24, 2020 at 14:24

2 Answers 2

2

If your array has sequential integer keys, then get the current key and then add or subtract one. If it is already at the first position then return the last one or if it is at the last position return the first one. That may not be the behavior you want, so just change what's after the ?? to whatever you want if next or previous don't exist:

$key  = array_search($_GET['page'], $blog_ids);
$prev = $blog_ids[$key-1] ?? end($blog_ids);
$next = $blog_ids[$key+1] ?? reset($blog_ids);

For other arrays just re-index first with:

$blog_ids = array_values($blog_ids);

Also, after re-indexing and searching you could get all 3 with:

list($prev, $curr, $next) = array_slice($blog_ids, $key-1, 3);
Sign up to request clarification or add additional context in comments.

Comments

-1

PHP has functions for this:

https://www.php.net/manual/en/function.prev.php

https://www.php.net/manual/en/function.next.php

hth

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.