how to get top 3 values in php array and their index

后端 未结 5 812
醉梦人生
醉梦人生 2021-01-18 21:45

I want to get the highest value, the second highest value and the third highest value

For example, I have an array like:

$n = array(100,90,150,200,199,

5条回答
  •  借酒劲吻你
    2021-01-18 22:22

    You can achieve it by using arsort() and array_keys() functions:

    • arsort() sorts an array in reverse order and maintains index association
    • array_keys() returns all the keys or a subset of the keys of an array

    Process array:

    $n = array(100,90,150,200,199,155,15,186);
    arsort($n);
    $keys = array_keys($n);
    

    Get top 3 values:

    echo $n[$keys[0]];
    echo $n[$keys[1]];
    echo $n[$keys[2]];
    

提交回复
热议问题