简体   繁体   中英

php how to navigate to previous and next value in an array

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM