How random is PHP's shuffle function?

后端 未结 7 1951
眼角桃花
眼角桃花 2020-12-03 21:12

Does anyone know what\'s the randomness of PHP\'s shuffle() function? Does it depend on the operating system? Does it use PHP\'s own seeder?

Is it poss

相关标签:
7条回答
  • 2020-12-03 21:56

    Works with associative and numeric arrays:

    function mt_shuffle_array($array) {
        $shuffled_array = [];
        $arr_length = count($array);
    
        if($arr_length < 2) {
            return $array;
        }
    
        while($arr_length) {
            --$arr_length;
            $rand_key = array_keys($array)[mt_rand(0, $arr_length)];
    
            $shuffled_array[$rand_key] = $array[$rand_key];
            unset($array[$rand_key]);
        }
    
        return $shuffled_array;
    }
    
    $array = [-2, -1, 'a' => '1', 'b' => '2', 'c' => '3', 11, 'd' => '4', 22];
    $shuffled_array = mt_shuffle_array($array);
    

    0 讨论(0)
提交回复
热议问题