tags:

views:

64

answers:

3

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.

+5  A: 

array_search() should save you the loop.

Matchu
In addition, `array_keys()` may be of use if you need more than just the first one: http://php.net/manual/en/function.array-keys.php
Topher Fangio
The question says it's definitely unique, but neat. I never knew that array_keys took a second parameter.
Matchu
Works like I charm. I even did some quick microtime() tests and it runs about twice as fast on a small array. No idea how it would fare on a large one. :)
Erik
+1  A: 

You are looking for the array_search function: http://www.php.net/manual/en/function.array-search.php.

$key = array_search('banana', $items);
danielrsmith
A: 

http://www.php.net/manual/en/function.array-search.php

$current_key=array_search('banana',$items);
MindStalker