Forum Moderators: coopster

Message Too Old, No Replies

Finding the 'next' key in an array

without stepping through the entire array

         

penders

12:43 pm on Apr 25, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Given an arbitrary array key in an associative array is there a more efficient way of finding the next array key without having to step through the array foreach() style?

Currently I'm doing something like:

$nextkey = false; 
$foundit = false;
foreach($myarray as $key => $value) {
if ($foundit) {$nextkey = $key; break;}
if ($key == $searchkey) {$foundit = true;}
}
return $nextkey;

I was hoping I could reset() the array to a particular key, and then perhaps do a next(), but this doesn't seem to be possible?

mcavic

2:37 pm on Apr 25, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hmm, I don't see another way.

joelgreen

7:59 pm on Apr 25, 2007 (gmt 0)

10+ Year Member



I searched few forums and could not find any solution which would be smarter than yours. All are based on foreach of while loops.

whoisgregg

9:45 pm on Apr 25, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



There's a function to set the array's internal pointer to a particular index on the PHP manual page for Array functions [us.php.net] in the comments. It uses a loop as well, but you may find it's implementation to be helpful. :)

Added: The comment is by a "Colin" at 10-Feb-2007 12:31.