View Full Version : Associative array - not the right way to go?

08-12-2007, 12:19 AM
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...

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

$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! :eek:

08-12-2007, 12:31 AM
You could just use something like array_keys to find the key name i.e.

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

print $array[$vals[0]];

08-12-2007, 12:48 AM
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 (http://www.php.net/array_keys) 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 :thumbsup:

08-12-2007, 12:50 AM
Yeh sorry about that, i realised it was wrong, i did try the new version and believe it should work!