dongxia4880 2012-03-22 15:41
浏览 139
已采纳

继续生成随机数,直到一个不存在 - PHP

I have a string with a lot of different numbers. I am trying to create a new random number and add it to the string.

The part I need help with is "if the number already exists in the string, create a new random number, and keep doing it until a number is created that does not yet exist in the string".

// $string contains all the numbers separated by a comma
$random = rand(5, 15);

$existing = strpos($string, $random);

if ($existing !== false) { $random = rand(5, 15); }

$new_string = $string.",".$random;

I know this isn't quite right as it will only check if it's existing once. I need it to keep checking to make sure the random number does not exist in the string. Do I use a while loop? How would I change this to work properly?

Your help is much appreciated.

  • 写回答

2条回答 默认 最新

  • douna6802 2012-03-22 15:59
    关注

    A solution that works like Endijs ... but I want to post that :)

    $string = '6,7,8';
    $arr = explode(',', $string);
    
    $loop = true;
    while($loop) {
        $randomize = rand(5, 15);
        #var_dump($randomize);
        $loop = in_array($randomize, $arr);
        if (!$loop) {
            $arr[] = $randomize;
        }
    }
    
    $newString = implode(',', $arr);
    var_dump($newString);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器