3

This seems so easy but i cant figure it out

$users_emails = array(
'Spence' => '[email protected]', 
'Matt'   => '[email protected]', 
'Marc'   => '[email protected]', 
'Adam'   => '[email protected]', 
'Paul'   => '[email protected]');

I need to get the next element in the array but i cant figure it out... so for example

If i have

$users_emails['Spence']

I need to return [email protected] and if Its

$users_emails['Paul'] 

i need start from the top and return [email protected]

i tried this

$next_user = (next($users_emails["Spence"]));

and this also

 ($users_emails["Spence"] + 1 ) % count( $users_emails )

but they dont return what i am expecting

4
  • Are associative arrays ordered? Commented May 26, 2011 at 16:20
  • Is the name you're using in the key a one-time input, or do you need to print all the values out with their corresponding emails? Commented May 26, 2011 at 16:20
  • Might want to create a circular linked list for this. Commented May 26, 2011 at 16:21
  • you have to move the array_pointer to next and prev your self read the Array functions and its there how to iterate array manually Commented May 26, 2011 at 16:25

3 Answers 3

7
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) { ...
Sign up to request clarification or add additional context in comments.

Comments

4

You could do something like this:

$users_emails = array(
'Spence' => '[email protected]', 
'Matt'   => '[email protected]', 
'Marc'   => '[email protected]', 
'Adam'   => '[email protected]', 
'Paul'   => '[email protected]');

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.