Home  >  Article  >  Backend Development  >  PHP uses iterative and recursive methods to create cascading directories (for learning, during development you should write mkdir('./a/b/c/d/e',0777,true)_PHP tutorial

PHP uses iterative and recursive methods to create cascading directories (for learning, during development you should write mkdir('./a/b/c/d/e',0777,true)_PHP tutorial

WBOY
WBOYOriginal
2016-07-14 10:10:151309browse

[php]

/*
Create directories recursively using an iterative method
In fact, mkdir can create directories recursively after PHP5.0.0.
The main thing here is to learn iteration by myself, so I started by creating a cascading directory.
During development, you should write mkdir('./a/b/c/d/e',0777,true);
Official description:
Recursive functions can be called in PHP.
But avoid recursive function/method calls exceeding 100-200 levels,
Because it may crash the stack and terminate the current script.
*/
function it_mk_dir($path){
//Define an array to store tasks that require work creation directories
$arr = array();
//If the directory to be created does not exist, it means there is a task to be added
while(!is_dir($path)){
array_unshift($arr,$path);
//Add the task and get the parent directory
$path = dirname($path);
}
//If there is no task (ie: the directory that needs to be created already exists)
if(empty($arr)){
return true;
}
//Otherwise start executing the task
foreach($arr as $k => $v){
//Using the array_unshift push method above, you can call it directly like this
mkdir($v) ? print('Creation of '.$v.' directory successful!
'):print('Creation failed ->'.$v.'
');
}
return true;
}
[php]
/*
Recursive method creation
*/
function mk_dir($path){
if(is_dir($path)){
return true;
}
//The parent directory exists or needs to be created to call mkdir
return is_dir(dirname($path)) || mk_dir(dirname($path)) ? mkdir($path) : false;
}
it_mk_dir('./a/b/c/d/e/f/g');

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477541.htmlTechArticle[php] ?php /* Using the iterative method to recursively create directories is actually already possible with mkdir after PHP5.0.0 Directories are created recursively. The main thing here is to learn iteration by yourself, so start by creating cascading directories...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn