How to create folders in PHP - names of folders stored in array?

151 views Asked by At

I have the code below. I want to create folders if they are not already created. Can I do it more elegant way? More dynamic? Can I call mkdir() this way?

$array = array('Stylesheets' => 'css', 'Javascript' => 'js') //ETC
    mkdir($array, 0777, true);

Thanks.

<?php
header('Content-Type: text/html; charset=utf-8'); 
?>

Creating directories:

<?php

if ( !file_exists('js') ) {
    mkdir('js', 0777, true) ;
    echo 'Js directory has been created.';
}

else
    echo 'Js directory already exists.';

if ( !file_exists('css') ) {
    mkdir('css', 0777, true) ;
    echo 'Css directory has been created.';
}

else
    echo 'Css directory already exists.';

if ( !file_exists('img') ) {
    mkdir('img', 0777, true) ;
    echo 'Img directory has been created.';
}

else
    echo 'Img directory already exists.';

?>
1

There are 1 answers

0
Rajdeep Paul On BEST ANSWER

Loop through the array to create directories dynamically, like this:

$array = array('Stylesheets' => 'css', 'Javascript' => 'js');

foreach($array as $dir){
    if ( !file_exists($dir) ) {
        mkdir($dir, 0777, true) ;
        echo $dir . ' directory has been created.';
    }
}