如何在没有任何 for 循环的情况下增加一个值,但基于文件在 PHP 中 运行 的次数

How to increment a value without any for loop but based on number of times the file is run in PHP

我有一个脚本,当它 运行s 时,它会在某个目录中创建一个新文件。创建新文件时,它会检查文件是否存在:

$filecount = 0;
if (! file_exists ( SOME_DIR . $fileName )) {
    echo "not there";
    //so save normally
} else {
    echo "there";
    $fileName  = $fileName."_" .$file_count++.".txt";
    // save with number at the end
}

目前,当文件运行多次时,它只在第一次用数字保存,因为变量$filecount再次设置为0

是否有任何变通方法可以在名称重复时递增 filename

您需要在某处存储脚本的运行次数。如果您已经在编写文件,我会使用纯文本文件来存储运行次数。

其他选项是使用时间戳作为文件名去重器。

你可以这样做

<?php
define('SOME_DIR', '');

$fileName = 'file';
if (! file_exists ( SOME_DIR . $fileName.'.txt' )) {
    echo "not there";
    //so save normally
}
else{
    $files = glob(SOME_DIR.$fileName.'_*.txt');
    $counter = count($files)+1;
    echo "there";
    $fileName  = $fileName."_" .$counter.".txt";
    echo $fileName;
    // save with number at the end
}

经过测试,对我来说效果很好

define('SOME_DIR', __DIR__ . '/');
$basename = 'test.txt';
$path = SOME_DIR . $basename;

// Consider clearing stat cache before using `file_exists` and similar
// functions that run `stat`, or `lstat` system calls under the hood.
clearstatcache(true, $path);

if (file_exists($path)) {
  $filename = pathinfo($basename, PATHINFO_FILENAME);
  $ext      = pathinfo($basename, PATHINFO_EXTENSION);

  $files = glob(SOME_DIR . "${filename}_[0-9]*.${ext}", GLOB_BRACE);

  $basename = sprintf(
    '%s_%d.%s',
    $filename,
    (count($files) + 1),
    $ext
  );

  $path = SOME_DIR . $basename;
}

// Replace with your logic
touch($path);