Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array get next/previous elements

Tags:

arrays

php

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.

like image 214
Sotos Avatar asked May 12 '26 22:05

Sotos


2 Answers

$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!

like image 97
Rolando Cruz Avatar answered May 15 '26 10:05

Rolando Cruz


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

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

like image 44
Ernestas Stankevičius Avatar answered May 15 '26 10:05

Ernestas Stankevičius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!