Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Associative array - not the right way to go?

1. ## Associative array - not the right way to go?

I have a list of word/number pairs. I need to retrieve the word that has the highest number associated with it.

I have put this list into an associative array...

PHP Code:
``` \$array['apple'] = '12'; \$array['orange'] = '3'; \$array['pear'] = '50';  ```
...and ordered it using arsort() so that "pear" in this case is the first value, then hit a brick wall when I realised that echoing \$array[0] didn't work on an associative array. Indeed, why would it?

Is there a simple way to retrieve the top value after it's sorted, or do you always need to know the name of the key to manipulate associative arrays?

Else, do I need to look into multidimensional arrays? Something like...

PHP Code:
``` \$array[0] = array('apple' => '12'); \$array[1] = array('orange' => '3'); \$array[2] = array('pear' => '50');  ```
At which point, I'm not clear on how this would be sorted based on the values of the nested arrays, and how you would then specify to retrieve the key of the nested array of the first key of the original array!

• You could just use something like array_keys to find the key name i.e.

PHP Code:
``` \$vals = array_keys(\$array); print \$vals[0];  ```
That would give you the key name of the first item and to get the value you could just:

PHP Code:
``` print \$array[\$vals[0]];  ```

• Thanks for taking a shot at this, but that first bit of code throws an error. I tried a couple of variations but couldn't get them to work, it looks like you still need to know the key name or the value name to use this - neither of which I will (outside of the simplistic example above, that is).

EDIT: You edited your post while I was replying. Let me try this edited code...

EDIT AGAIN: That did the job, thanks! To anyone else reading this in the future, this solution using array_keys applies to the associative array I mentioned, not the multidimensional one. Thanks anarchy

• Yeh sorry about that, i realised it was wrong, i did try the new version and believe it should work!

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•