next element in a associative php array

后端 未结 3 866
孤城傲影
孤城傲影 2021-01-22 04:45

This seems so easy but i cant figure it out

$users_emails = array(
\'Spence\' => \'spence@someplace.com\', 
\'Matt\'   => \'matt@someplace.com\', 
\'Marc\'         


        
相关标签:
3条回答
  • 2021-01-22 05:01

    You would be better storing these in an indexed array to achieve the functionality you're looking for

    0 讨论(0)
  • 2021-01-22 05:16

    You could do something like this:

    $users_emails = array(
    'Spence' => 'spence@someplace.com', 
    'Matt'   => 'matt@someplace.com', 
    'Marc'   => 'marc@someplace.com', 
    'Adam'   => 'adam@someplace.com', 
    'Paul'   => 'paul@someplace.com');
    
    $current = 'Spence';
    $keys = array_keys($users_emails);
    $ordinal = (array_search($current,$keys)+1)%count($keys);
    $next = $keys[$ordinal];
    print_r($users_emails[$next]);
    

    However I think you might have an error in your logic and what you are doing can be done better, such as using a foreach loop.

    0 讨论(0)
  • 2021-01-22 05:20
    reset($array);
    while (list($key, $value) = each($array)) { ...
    

    Reset() rewind the array pointer to the first element, each() returns the current element key and value as an array then move to the next element.

    list($key, $value) = each($array);
    // is the same thing as
    $key = key($array); // get the current key
    $value = current($array); // get the current value
    next($array); // move the internal pointer to the next element
    

    To navigate you can use next($array), prev($array), reset($array), end($array), while the data is read using current($array) and/or key($array).

    Or you can use foreach if you loop over all of them

    foreach ($array as $key => $value) { ...
    
    0 讨论(0)
提交回复
热议问题