Link to home
Start Free TrialLog in
Avatar of thepadders
thepadders

asked on

Getting the next key in an array

I have an array where the keys are numeric but not sequential, so its:

23, 354, 545, 2333 etc

I now have the value for a key, say 354 and I want to get the next key, in this case 545.

What is the best way to do this? Do I need to loop through the array, match the key and then get the next match. Is there a more efficient method?
Avatar of ldbkutty
ldbkutty
Flag of India image

Since you need just the key - value pair, foreach loop will serve good:

$myKey = false;
foreach($my_array as $key=>$value)
{
     if($myKey) {
        echo "$key : $value";
        $myKey = false;
        // break;
     }
     if($value == YOUR_VALUE) {
        $myKey = true;
     }
}

If you want to get the key for a value, array_search ( http://www.php.net/array_search ) function is handy.
what about key(next($array)) ?
Avatar of thepadders
thepadders

ASKER

ZhaawZ,

How do you move the internal pointer of an array to a specific key?
ASKER CERTIFIED SOLUTION
Avatar of ZhaawZ
ZhaawZ
Flag of Latvia 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
Is that any different/better than the foreach method?
Yes, foreach creates a copy of the array and loops through that copy. It is NOT as fast as ZhaawZ method. So go with it.
Hi

I would just use the basic array functions with a loop, but when working with big array(s) it not very good when the key you are matching is at the end of the array! With big arrays use a preg_ function with implode! This way you don't need to use a loop or do 100(s) or even thousands of if(s) or repeated array function calls in that loop!

example...

<?

$arr = array ( 23 => '1st', 354 => '2nd', 545 => '3rd', 2333 => '4th' );

$key = 545;

if ( isset ( $arr[$key] ) )
{
      $next = preg_replace ( "!^.*?(" . $key . ")\|?(.*)\|?!", "\\2", implode ( '|', array_keys( $arr ) ) );

      if ( ! empty ( $next ) )
      {
            echo 'Next key: ' . $next . ' => ' . $arr[$next];
      }
      else
      {
            echo 'key: ' . $key . ', is the last element in array (arr) no next key';
      }
}
else
{
      echo $key . 'does not exit!';
}

?>

Suzanne
Avatar of Roonaan
@Suzanne:

Wouldn't your method also load keys in subarrays?

Lets say we would have
array(1 => array("test" => 1, "test2"=>2), 2, 3, 4);

Your code would show us that "test2" is the next key following key "test", although array["test2"] does not work.

-r-