Glossary

Recursion

Recursion is a function that calls itself to solve a smaller subproblem. Classic uses: tree traversal, divide-and-conquer, mathematical sequences.

Two mandatory elements

Example: scanning directories

function scanDir(string $path): array {
  $result = [];
  foreach (scandir($path) as $item) {
    if ($item === '.' || $item === '..') continue;
    $full = "$path/$item";
    $result[] = is_dir($full) ? scanDir($full) : $full;
  }
  return $result;
}

Recursion vs Iteration

Recursion is elegant for problems with a naturally tree-like structure. But each call consumes stack space. Deep recursion can cause a stack overflow. For large depths, use an iterative approach with an explicit stack.