Sotos
Sotos

Reputation: 146

Array get next/previous elements

i have this array of id's: $products=array(2151, 2563, 2015, 1986, 1985);

What i want is to build a function that will return the next and the previous item each time i pass an id. For example when i have lets say the 2563-id to get a response with 2151 & 2015.

Any suggestions will be appreciated.

Upvotes: 2

Views: 7586

Answers (2)

Ernestas Stankevičius
Ernestas Stankevičius

Reputation: 2493

I case you would have spec keys, then next() and prev() functions is better.

http://php.net/manual/en/function.next.php

Upvotes: 1

Rolando Cruz
Rolando Cruz

Reputation: 2784

$index = array_search($id, $products);
if($index !== FALSE)
{
  $next = $products[$index + 1];
  $previous = $products[$index - 1];
}

Then you do the checks since $products[$index +/- 1] will not always exist!

Upvotes: 9

Related Questions