Getting lowest value in array or random value if all is the same?

后端 未结 2 2050
半阙折子戏
半阙折子戏 2021-01-26 10:41

I have an array like so

Array
(
    [5] => 0
    [6] => 0
)

the key 5 and key 6 are user id\'s. the value 0 for both the keys are the num

相关标签:
2条回答
  • 2021-01-26 11:23

    What you need is min() for the lowest value in the array and array_rand() to get a random entry out of the array.

    $yourArr = array(4, 4, 3, 5);
    
    $lowestEntry = min($yourArr);
    $duplicateEntries = array_keys($yourArr, $lowestEntry);
    
    echo (count($duplicateEntries) > 1)?$yourArr[array_rand($duplicateEntries, 1)]:$lowestEntry;
    
    0 讨论(0)
  • 2021-01-26 11:34

    Let's say your array is $arr

    $mini = min($arr);
    $user = array();
    foreach ($arr as $key => $val){
        if ($val == $mini){
            // find the user with minimum value
            $user[] = $key;
        }
    }
    // print the user with minimum value
    echo array_rand($user, 1).' '.$mini;
    
    0 讨论(0)
提交回复
热议问题