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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化