• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 244
  • Last Modified:

Moving an associative array pointer by a known key

I have an associative array of lets say fruits and vegies:
array (apple => red, orange=> orange, celery=>green);
and I know the fruit / veggie and wanted to use the next() and prev() php functions.

Besides using a foreach loop, is there a way to move the array pointer to that key?

Thanks in advance
0
bergstrom_davin
Asked:
bergstrom_davin
2 Solutions
 
nizsmoDeveloperCommented:
you can put the code into a for loop or a while loop, and determine the length of the array (count($array)) then you can utilize the next($array) to move the pointer forward or prev($array) to move backwards as you like.
0
 
nplibCommented:
you could just be like

$fruits = array (apple => red, orange=> orange, celery=>green);

echo $fruits['celery'];

and it will output green.

if you already know the fruit in question
any more I need more details on what you want.
0
 
hernst42Commented:
> Besides using a foreach loop, is there a way to move the array pointer to that key?
no the only functions that move the internal array pointers are: end, prev, next, each, reset
All other operations on the array typical destroy/reset the internal array pointer

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
bergstrom_davinAuthor Commented:
Thank you all for you work.

I plan on moving via prev, next, reset ... But would like to start in the middle of the array. If I am understanding you correctly hernst42, the only way to get to the middle will be using a foreach loop or something similar, then when I hit the key I can use the next and prev commands.
0
 
hernst42Commented:
> If I am understanding you correctly hernst42, the only way to get to the middle will be using a foreach loop or something similar, then when I hit the key I can use the next and prev commands.
Yes
0
 
nplibCommented:
that's the only way to move the pointer through the array,

but you can access any part of an array at any time, just by referring to it's pointer.

$bob = array(1, 2, 3);
echo $bob['1']; //output is 2
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now