Generate array of random unique numbers in PHP

前端 未结 7 911
再見小時候
再見小時候 2020-12-11 15:09

I\'m trying to generate an array of random numbers from 0-n then shuffle (but ensure that the keys and values DO NOT match).

For example:

0 => 3
1         


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-11 15:41

    This will generate an array with 10 random numbers from 0 to 100:

    array_map(function () {
           return rand(0, 100);
       }, array_fill(0, 10, null)
    );
    

    Result:

    array(10) {
      [0]=>
      int(15)
      [1]=>
      int(97)
      [2]=>
      int(20)
      [3]=>
      int(64)
      [4]=>
      int(57)
      [5]=>
      int(38)
      [6]=>
      int(16)
      [7]=>
      int(53)
      [8]=>
      int(56)
      [9]=>
      int(22)
    }
    

    Explanation:

    • array_fill(0, 10, null) will generate an array with 10 empty items
    • array_map Applies the callback (first argument) to each item of the array it receives (second argument). In this example, we just return a random number for each array item.

    Playground: https://3v4l.org/FffN6

提交回复
热议问题