Home  >  Article  >  Backend Development  >  PHP uses recursion to list all files and directories

PHP uses recursion to list all files and directories

怪我咯
怪我咯Original
2017-07-16 10:17:532491browse

What is Recursion

The programming technique in which a program calls itself is called recursion. Recursion as an algorithm is widely used in programming languages. A procedure or function has a method of directly or indirectly calling itself in its definition or description. It usually transforms a large and complex problem into a smaller problem similar to the original problem. To solve the problem, the recursive strategy only needs a small amount of programs to describe the multiple repeated calculations required in the problem-solving process, greatly reducing the amount of program code. The power of recursion lies in defining an infinite collection of objects with a finite number of statements. Generally speaking, recursion requires boundary conditions, a recursive forward segment, and a recursive return segment. When the boundary conditions are not met, the recursion advances; when the boundary conditions are met, the recursion returns.

The following example is php using recursion to list all files and directories

<?php 

function tree($directory) 
{ 
$mydir=dir($directory); 
echo "<ul> 
"; 
while($file=$mydir->read()){ 
if((is_dir("$directory/$file")) AND ($file!=".") AND ($file!="..")) 
{echo "<li><font color="#ff00cc"><b>$file</b></font></li> 
"; 
tree("$directory/$file"); 
} 
else 
echo "<li>$file</li> 
"; 
} 
echo "</ul> 
"; 
$mydir->close(); 
} 
//start the program 
echo "<h2>目录为粉红色</h2> 
"; 
tree("."); 
?>

The above is the detailed content of PHP uses recursion to list all files and directories. For more information, please follow other related articles on the PHP Chinese website!

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