...

View Full Version : How to get minimum value of an array?



XtremeGamer99
09-19-2009, 09:21 AM
Trying to get back into coding, and I'm currently working on a new project. Let me get right to the chase.

Lets say I have an array:
[3017496] => 15
[3017678] => 9
[3017114] => 8
[3017297] => 10
[3017428] => 9
[3017440] => 6
[3017683] => 5
[3017306] => 11
[3017461] => 8
[3017529] => 6
[3017683] => 5

I'm trying to return the minimum values of this array. min() work pretty well, but it only returns an number, and it doesn't discriminate over how many of the lowest value there are.

Taking that array as an example, min() only returns 5. However, I need this:

[3017683] => 5
[3017683] => 5

I could always just make a foreach function and compare all the values while throwing out ones higher than others until it comes down to what I need, but I wanted to ask here to see if there's already a function to do this.

Thanks!

FWDrew
09-19-2009, 11:55 AM
Not the most elegant solution but will work for what you explained, I'm assuming the values will always be numeric so I set strict comparison to true.



$test_array = array(3017496 => 15, 3017683 => 5, 3017306 => 11, 3017623 => 5, 3017114 => 8);
$min_val = min($test_array);
$arr_search = array_keys($test_array, $min_val, true);
print_r($arr_search);

kbluhm
09-20-2009, 01:43 AM
function min_values( Array $array )
{
return
array_intersect_key(
$array,
array_count_values(
array_keys(
$array,
min( $array )
)
)
);
}

// usage
$min_values = min_values( $values );

XtremeGamer99
09-28-2009, 06:50 AM
Thank you all for the help. =)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum