PHP Get Highest Value from Array

前端 未结 16 1341
耶瑟儿~
耶瑟儿~ 2020-11-28 07:05

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

16条回答
  •  再見小時候
    2020-11-28 07:38

    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");
    

提交回复
热议问题