Creation of Recursive Folders

Asked

Viewed 72 times

1

The Problem:

I wonder if there is a more practical way than using the control structures IF/ELSE for creation of folders recursively, based on the inputs that the user typed.

Context:

For example, in my script, I receive the data, validate and sanitize the later ones, and then I create folders with the data of the fields informed, so far so good, but the problem is that some fields are not required to be typed, so if I have, for example 4 fields:

Name, Enterprise, City, State

I wonder if there’s any other way than IF/ELSE:

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

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

  • And what should happen if there is some empty field?

  • It should ignore the $dir variable field if the name field is empty: $dir="uploads/{$empresa}/{$cidade}/{$estado}/"; and so on until all fields are checked

1 answer

1


A practical way (a few lines) is to create a vector with the values of the variables and filter them with the function array_filter. Then you can unify the remaining values with the function implode. Take 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"

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

You can see the code working here or here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.