Returning Value from Max(Key) in Array

learning_brain

New Member
Messages
206
Reaction score
1
Points
0
Interesting one this and I have searched high and low for an answer...

I have an associative array where image types are given a score.

The array is set up in a loop so that the score is used as the key and the value is the name of the image type.

PHP:
$imageScores [$score] = $imageType;

I am trying to return the image type (i.e. the value) from that array where it has the highest key (score).

I can't use a simple max() because it will only return a max value and not a max key.

Am I doing this the wrong way round? Should I set up ...

PHP:
$imageScores[$imageType] = $score;

.. I can then easily obtain the highest score, but how do I get the associated key image type?

It's probably simple but I can't get my head round it.

Any help would be appreciated.

Richard
 
Last edited:

lemon-tree

x10 Minion
Community Support
Messages
1,420
Reaction score
46
Points
48
Try using krsort, it'll sort the array descending by the key rather than the value:
Code:
//Setup your array:
$imageScores[$score] = $imageType;
//etc

//Sort by key, max score is now the first item in the array
krsort($imageScores, SORT_NUMERIC);

//Get the first item in the array, there are hundreds of ways you could do this and this is just one:
$maxValue = reset($imageScores);
If you need the key (score) as well as the value (as I suspect you might), the reset() method will not work and you may have to do something like a foreach or extract the key values:
Code:
//Setup your array:
$imageScores[$score] = $imageType;
//etc

//Get the scores as an array
$scoresArray = array_keys($imageScores);

//Get the max value
$maxKey = max($scoresArray);
$maxValue = $imageScores[$maxKey];
There are probably hundreds of other ways of doing it too.
 
Last edited:

learning_brain

New Member
Messages
206
Reaction score
1
Points
0
This is perfect - the 2nd method is ideal and can't believe I couldn't get my head round that.

I've also changed the scoring to percentage which works even better!

Thanks lemon-tree...yet again.
 
Top