I have a list of items in a particular order so I've decided to store them in an array
$items = array(
"apple",
"banana",
"pear"
);
If the program is called with the parameter "banana" I need to be able to say "apple" comes before and "pear" comes after. Currently I'm doing something like this:
foreach($items as $k=>$v) { if ($v == "banana") { $current_key = $k }
So now I know that $current_key -1 is previous and +1 is next. It works, it just FEELS ugly to iterate over the entire array. Is there a better way to do this?
UPDATE In case anyone cares, I decided to do a few quick tests to see how fast the ways of getting the information were. Over 1000 iterations, on an array of 6000 items, microtime retunred:
My Posted Way: 4.567 Array_Search: 2.749
While I was thinking I also tried an approach that stored the data in a array of arrays like:
$items['banana']['next'] = 'pear';
$items['banana']['prev'] = 'apple';
which was, of course, the winner by miles ( 0.0005 ). None of this is really relevant, I was just curious and thought to share with anyone who reads this.