有人可以解释这个do-while循环示例

时间:2013-12-04 06:40:19

标签: php loops do-while

我在php.net/manual上找到了这个例子,但是在示例中无法获得整个概念。 似乎这个例子缺少一些细节。

如果有人可以为我简化,我将不胜感激。这是一个例子:

我发现使用do-while循环最有用的方法是对文件存在进行多次检查。保证迭代意味着它将检查至少一次,我在使用简单的“while”循环时遇到了麻烦,因为它在结束时从未递增过。

我的代码是:

 $filename = explode(".", $_FILES['file']['name']); // File being uploaded
    $i=0; // Number of times processed (number to add at the end of the filename)
    do {

/* Since most files being uploaded don't end with a number,
  we have to make sure that there is a number at the end
  of the filename before we start simply incrementing. I
  admit there is probably an easier way to do this, but this
  was a quick slap-together job for a friend, and I find it
  works just fine. So, the first part "if($i > 0) ..." says that
  if the loop has already been run at least once, then there
  is now a number at the end of the filename and we can
  simply increment that. Otherwise, we have to place a
  number at the end of the filename, which is where $i
  comes in even handier */

  if($i > 0) $filename[0]++;
  else $filename[0] = $filename[0].$i;
  $i++;
} while(file_exists("uploaded/".$filename[0].".".$filename[1]));

if($i > 0)如何检测文件以数字结尾?循环是否引用了preg_match?

1 个答案:

答案 0 :(得分:0)

if ($i > 0)检测循环是否已经运行,因为它在第一次输入时为0且>所有后续迭代都为0

第一次迭代将始终将.0附加到文件名,因为$ i设置为0 然后,如果file.0.extension不存在,它将尝试递增$filename[0],作为字符串,它应该失败。

您可能打算比较$ filename [0]> 0对于任何非数字文件名(包括以数字结尾但包含字母的文件名),这将是假的,因为PHP执行的方式http://www.php.net/manual/en/language.types.string.php#language.types.string.conversion

我在那里看不到有关preg_match的内容。

如果您想要的是唯一的文件名,可以尝试使用http://php.net/manual/en/function.uniqid.php滚动自己的文件名(例如,请参阅php Unique filename when uploading