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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?