Creating Recursive Folders

1

The Problem:

I would like to know if there is a more practical way than using the IF/ELSE control structures to create folders recursively, based on the inputs that the user typed.

Context:

For example, in my script, I get the data, validate it and sanitize it later, and then I create folders with the fields data informed, so far so good, but the problem is that some fields are not mandatory to be so I have, for example, 4 fields:

Name , Company , City / em>

I would like to know if there is any way other than IF/ELSE :

$dir = "uploads/{$nome}/{$empresa}/{$cidade}/{$estado}/";       
    if(!is_dir($dir)):
            mkdir($dir, 0777, true);
    endif;

Create the folders with the data that was typed, ignoring the empty fields to avoid errors

    
asked by anonymous 03.04.2017 / 20:36

1 answer

1

A practical way (a few lines) is to create a vector with variable values and filter them with the array_filter ". You can then merge the remaining values with the implode function. See the example:

$nome    = "";
$empresa = "";
$cidade  = "foo";
$estado  = "bar";

$dir = 'uploads/' . implode('/', array_filter([$nome, $empresa, $cidade, $estado]));

var_dump($dir); // string(15) "uploads/foo/bar"

As natively an empty string is parsed as false by PHP, the array_filter function eliminates all empty values, then the rest are concatenated through the implode function.

You can see the code working here or here .

    
03.04.2017 / 21:54