做LOOP - 最好的方法

时间:2013-04-29 16:21:12

标签: php loops mkdir do-while

我有正确的PHP脚本来创建一个随机数,并在服务器上创建一个新文件夹,其名称为#。如果文件夹存在,脚本将停止。我无法弄清楚的是,如果文件夹已经存在,如何指示脚本生成一个新的随机#并再次尝试,直到它找到一个未使用的数字/文件夹。我认为do while是我正在寻找的但不确定我是否正确编写它(不想在服务器上测试它,因为害怕创建一个永远循环的mkdir命令)。

以下是正在使用的一次性代码

<?php
$clientid = rand(1,5);
while (!file_exists("clients/$clientid"))
{
mkdir("clients/$clientid", 0755, true);
exit("Your new business ID is($clientid)");
}
echo ("The client id is $clientid");
?>

以下是我正在考虑的do while - 这是正确的还是我需要以不同的方式做到这一点?

<?php

$clientid = rand(1,5);

do {mkdir("clients/$clientid", 0755, true);
    exit("Your new business ID is($clientid)");}

while (!file_exists("clients/$clientid"));
echo ("The client id is $clientid");

?>

3 个答案:

答案 0 :(得分:0)

问题是你只在循环外生成一个新数字。这意味着您最终会得到一个永不终止的循环。反转循环并在每次迭代时生成一个新数字:

$clientid = rand(1,5);
while (file_exists("clients/$clientid"))
{
    // While we are in here, the file exists. Generate a new number and try again.
    $clientid = rand(1,5);
}

// We are now guaranteed that we have a unique filename.
mkdir("clients/$clientid", 0755, true);
exit("Your new business ID is($clientid)");

答案 1 :(得分:0)

我会做这样的事情:

<?php
$filename = md5(time().rand()) . ".txt";
while(is_file("clients/$filename")){
    $filename = md5(time().rand()) . ".txt";
}
touch("clients/$filename");

答案 2 :(得分:0)

在while循环上测试代码时的有用提示;创建变量作为安全计数并增加它然后如果你的其他逻辑导致一个无限问题,它就会爆发,如下所示:

$safetyCount = 0;
while (yourLogic && $safeCount < 500){

//more of your logic
$safetyCount++;
}

显然,如果您需要500更低/更高,然后将其设置为任何,这只是确保您不会杀死您的机器。 :)

相关问题