dongpu1331 2015-04-09 21:53
浏览 42
已采纳

PHP如何获得与数组值不同的随机数

Example: I have an array with 3 values:

0 = 1
1 = 4
2 = 5

I want to get a random number like

$random = rand(1, 5);

But I need to get a number that is different from the array values. I need it to return 2 or 3.

  • 写回答

1条回答 默认 最新

  • dtpd58676 2015-04-09 22:03
    关注

    This should work for you:

    (Here I create the range from where you get your random number with range(). Then I get rid of these numbers which you don't want with array_diff(). And at the end you can simply use array_rand() to get a random key/number)

    <?php
    
        $blacklist = [1, 4, 5];
        $range = range(1, 5);
        $randomArray = array_diff($range, $blacklist);
        echo $randomArray[array_rand($randomArray, 1)];
    
    ?>
    

    output:

    2 or 3
    

    EDIT:

    Just did some benchmarks and the method with the loop is much slower than the code above!

    I created an array(blacklist) from 1...100'000 and a random number array from 1... 100'001.

    So that script should only create one/unique random number. With the loop method you get an error:

    Fatal error: Maximum execution time of 30 seconds exceeded

    And with the posted code above it takes 1.5 sec in average.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式