Php find max value in array with key
From an array that looks something like the following, how can I get the index of the highest value in the array. For the array below, the desired result would be '11'. Show
asked Sep 22, 2009 at 17:08
1 My solution is:
Note: If you are interested only in one key among all simply use $maxs[0] answered Sep 22, 2009 at 17:11
drAlberTdrAlberT 20.9k5 gold badges32 silver badges37 bronze badges 3
array_search() return values: Returns the key for needle if it is found in the array, FALSE otherwise. If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead. answered Sep 22, 2009 at 17:17
I know it's already answered but here is a solution I find more elegant:
and voila! answered Dec 13, 2013 at 13:58
David 天宇 WongDavid 天宇 Wong 3,3584 gold badges33 silver badges47 bronze badges 1 Other answers may have shorter code but this one should be the most efficient and is easy to understand.
answered Jun 3, 2017 at 12:52
luchaninovluchaninov 6,6196 gold badges57 silver badges75 bronze badges Something like this should do the trick
answered Sep 22, 2009 at 17:11
AistinaAistina 12.2k12 gold badges67 silver badges88 bronze badges 1 My solution to get the higher key is as follows:
mtk 12.8k15 gold badges70 silver badges111 bronze badges answered Mar 9, 2012 at 16:03
answered Sep 22, 2009 at 17:14
dnagirldnagirl 20k13 gold badges79 silver badges119 bronze badges Function taken from http://www.php.net/manual/en/function.max.php
Works like a charm answered Sep 22, 2009 at 17:29
3 How do I find the greatest value in an array in PHP?The max() function returns the highest value in an array, or the highest value of several specified values.
How do you find the max value in an array?Getting the maximum element of an array. const arr = [1, 2, 3]; const max = arr. reduce((a, b) => Math. max(a, b), -Infinity); ... . function getMaxOfArray(numArray) { return Math. max. apply(null, numArray); } ... . const arr = [1, 2, 3]; const max = Math. max(... arr);. What is Array_keys function in PHP?The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Syntax: array array_keys($input_array, $search_value, $strict) Parameters: The function takes three parameters out of which one is mandatory and other two are optional.
How do I find the smallest and largest number in an array in PHP?$min = min($numbers); $max = max($numbers); Option 2. (Only if you don't have PHP 5.5 or better) The same as option 1, but to pluck the values, use array_map : $numbers = array_map(function($details) { return $details['Weight']; }, $array);
|