Search code examples
phpmkdir

Append (1),(2) after duplicated folder name in PHP


Currently I have to create a folder similar in window file system.

For example: if folder is exist , add (1) at the end , if (1) is exist , add (2) at the end, the problem is , are there standard function in PHP or I have to write my own function?

if (isdir($folderPath)) {

        $folderPath =  ...special handling or any PHP standard function ..
        mkdir($folderPath);

}

From reading PHP manual , so far there is no similar parameter for me to handle this? Are there any function besides mkdir will work ?Thanks


Solution

  • I don't know of any function that does this. A bruteforece approach comes to mind:

    function make_filename($name) {
        if (file_exists($name)) {
            $i = 0;
            do {
                $testname = sprintf("%s (%d)", $name, ++$i);
            }
            while (file_exists($testname));
            return $testname;
        }
        return $name;
    }
    
    mkdir(make_filename("test"));
    

    I wouldn't recommend this if you expect a LOT of duplicated filenames.