开发者

How to get a index for a key I know to be unique in an array

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 开发者_JS百科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.


array_search() should save you the loop.


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

$key = array_search('banana', $items);


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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜