I\'m trying to get hold of the largest value in an array, while still preserving the item labels. I know I can do this by running sort(), but if I do so I simply lose the la
$abc=array("a"=>1,"b"=>2,"c"=>4,"e"=>7,"d"=>5);
/*program to find max value*/
$lagest = array();
$i=0;
foreach($abc as $key=>$a) {
if($i==0) $b=$a;
if($b<$a) {
$b=$a;
$k=$key;
}
$i++;
}
$lagest[$k]=$b;
print_r($lagest);
asort() is the way to go:
$array = array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
asort($array);
$highestValue = end($array);
$keyForHighestValue = key($array);
You need to use by ksort(array("a"=>1,"b"=>2,"c"=>4,"d"=>5)); for more info: http://www.w3schools.com/php/php_arrays_sort.asp
You could use max() for getting the largest value, but it will return just a value without an according index of array. Then, you could use array_search() to find the according key.
$array = array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
$maxValue = max($array);
$maxIndex = array_search(max($array), $array);
var_dump($maxValue, $maxIndex);
Output:
int 5
string 'd' (length=1)
If there are multiple elements with the same value, you'll have to loop through array to get all the keys.
It's difficult to suggest something good without knowing the problem. Why do you need it? What is the input, what is the desired output?
Here a solution inside an exercise:
function high($sentence)
{
$alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
$alphabet = array_flip($alphabet);
$words = explode(" ", $sentence);
foreach ($words as $word) {
$letters = str_split($word);
$points = 0;
foreach ($letters as $letter)
$points += $alphabet[$letter];
$score[$word] = $points;
}
$value = max($score);
$key = array_search($value, $score);
return $key;
}
echo high("what time are we climbing up the volcano");
// assuming positive numbers
$highest_key;
$highest_value = 0;
foreach ($array as $key => $value) {
if ($value > $highest_value) {
$highest_key = $key;
}
}
// $highest_key holds the highest value