Link to home
Start Free TrialLog in
Avatar of bergstrom_davin
bergstrom_davin

asked on

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
Avatar of Joe Wu
Joe Wu
Flag of Australia image

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.
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.
> 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

Avatar of bergstrom_davin
bergstrom_davin

ASKER

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.
ASKER CERTIFIED SOLUTION
Avatar of hernst42
hernst42
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial