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.

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c