what's the most efficient way to code php to return a key of an element with the maximum value in the array.
for example if i have an array
1=>2
2=>7
3=>8
4=>1
i want it to return 3
what's the most efficient way to code php to return a key of an element with the maximum value in the array.
for example if i have an array
1=>2
2=>7
3=>8
4=>1
i want it to return 3
call your array $numbers. Then $numbers[2]. It starts with 0.
I'm not sure if this is the most efficient way... (bad search algorithm) but it works.
<?
$myarray = array(0, 2, 7, 8, 400, 5, 3, 343, 43, 3);
$max_value = max($myarray);
for($i=0; $i<count($myarray); $i++)
{
if($myarray[$i] == $max_value)
$max_key = $i;
}
echo 'The max key is: ' . $max_key . ' with value: ' . $max_value;
?>
The results should be:
The max key is: 4 with value: 400
good good, that's my idea.. i was just wondering if there's a way to find a key of an element in the array without go thru the array.. there probably isn't.
Maybe array_search() could do the thing...
PHP.net :
array_search
(PHP 4 >= 4.0.5)array_search -- Searches the array for a given value and returns the corresponding key if successful
Description
mixed array_search ( mixed needle, array haystack [, bool strict])Searches haystack for needle and returns the key if it is found in the array, FALSE otherwise.
Note: Prior to PHP 4.2.0, array_search() returns NULL on failure instead of FALSE.
If the optional third parameter strict is set to TRUE then the array_search() will also check the types of the needle in the haystack.
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
wow, how could i have missed that. i even looked at that function. thanks!