Search code examples
phparraysrandomminimum

How to randomly get min value from Array?


I have an array with multiple similar minimum value. May I know how to randomly get one of the minimum value?

Here is my sample code:-

$aryNo = array(
                    0 => 34, 1 => 34, 2 => 51, 3 => 12, 4 => 12,
                    5 => 12, 6 => 56, 7 => 876, 8 => 453, 9 => 43,
                    10 => 12
);
$b = array_keys($aryNo, min($aryNo));  //Here only can get 1 value.
$intNo = $b[0];

May I know how to get min value list (3 => 12, 4 => 12,5 => 12,10 => 12) and randomly pick one of them so that I can set in $intNo?


Solution

  • $aryNo = array(
        0 => 34, 1 => 34, 2 => 51, 3 => 12, 4 => 12,
        5 => 12, 6 => 56, 7 => 876, 8 => 453, 9 => 43,
        10 => 12
    );
    $b = array_keys($aryNo, min($aryNo));  //Here only can get 1 value.
    
    // Taking a random KEY from $b
    $key = array_rand($b);
    
    // Taking a KEY from $aryNo which is under `$key`
    echo $b[$key];
    
    // Taking a VALUE from `$aryNo` which is under `$b[$key]`
    echo $aryNo[$b[$key]];
    

    The fiddle.