doujionggan9570 2017-09-20 16:12
浏览 43
已采纳

mt_rand PHP - 几行数

is it possible to customize mt_rand to a function which gives me a line of numbers without repeats.

For example mt_rand(1,5) should give me 4,2,3,1,5 or something like that.

  • 写回答

2条回答 默认 最新

  • douzhaobo6488 2017-09-20 16:25
    关注

    This achieves what you ask in your question:

    $results = range(1, 5);
    shuffle($results);
    


    For more complex needs, you can use Faker.

    For instance the randomElements() method, here picking 5 non-duplicate numbers in the 1-10 range:

    $faker = \Faker\Factory::create();
    
    $results = $faker->randomElements(range(1, 10), 5, false);
    

    (though, this can also be done with regular PHP easily:)

    $pool = range(1, 10);
    shuffle($pool);
    
    $results = array_slice($pool, 0, 5);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?