← Back to PHP Course | Chapter 5: Functions | Lesson 6 of 10

PHP Recursion

Recursion दो mirrors के बीच खड़े होने या nested Russian dolls खोलने जैसा है: एक function एक बड़े job को उसी job की एक छोटी copy खुद को सौंपकर solve करता है। यह तब रुकता है जब सबसे छोटी doll मिल जाए।
Syntax
php
function function_name($n) {
    if ($n <= 0) {          // base case
        return base_value;
    }
    return function_name($n - 1);   // recursive case
}

Recursion का Introduction

एक recursive function वह है जो खुद को call करता है, आमतौर पर किसी problem को उसी problem के एक छोटे version में तोड़ने के लिए।

हर recursive function को एक base case चाहिए — एक condition जहाँ यह खुद को call करना बंद कर दे और सीधे एक answer return कर दे — नहीं तो यह हमेशा के लिए खुद को call करता रहेगा।

उदाहरण: Introduction to Recursion

php
<?php
// Define the function `countDown` taking `$n`
function countDown($n) {
    // Check whether `$n <= 0`
    if ($n <= 0) {
        // Print "Done!\n" to the output
        echo "Done!\n";
        // Return early, with no value
        return;
    }
    // Print `$n . "\n"` to the output
    echo $n . "\n";
    // Call `countDown($n - 1)`
    countDown($n - 1);
}
// Call `countDown(3)`
countDown(3);
?>

Base Case और Recursive Case

Base case वह specific condition है जो recursion को पूरी तरह खत्म करती है, बिना किसी आगे के self-call के एक value return करते हुए।

Recursive case बाकी सब कुछ है: यह function को फिर से ऐसे arguments के साथ call करता है जो measurably उस base case को आख़िरकार satisfy करने के करीब हों।

उदाहरण: Base Case and Recursive Case

php
<?php
function factorial($n) {
    if ($n <= 1) {
        return 1; // base case
    }
    return $n * factorial($n - 1); // recursive case
}
echo factorial(5);
?>

Fibonacci Sequence

Fibonacci sequence को recursively compute करना — जहाँ हर number इससे पहले के दो का sum है — code में mathematical definition को लगभग exactly mirror करता है, यही exactly वजह है कि यह इतना common पहला example है, भले ही naive recursive version बड़े inputs के लिए inefficient हो।

उदाहरण: Fibonacci Sequence

php
<?php
// Define the function `fibonacci` taking `$n`
function fibonacci($n) {
    // Check whether `$n <= 1`
    if ($n <= 1) {
        // Return `$n` from this function
        return $n;
    }
    // Return `fibonacci($n - 1) + fibonacci($n - 2)` from this function
    return fibonacci($n - 1) + fibonacci($n - 2);
}
// Print `fibonacci(6)` to the output
echo fibonacci(6);
?>

Nested Structures Parse करना

Recursion उन problems के लिए suit करता है जिनकी depth पहले से नहीं पता, जैसे एक folder tree या एक nested category structure में चलना — आप आसानी से predict नहीं कर सकते कि nesting कितनी levels गहरी जाती है, इसलिए nested loops की एक fixed संख्या काम नहीं करेगी, लेकिन प्रति level खुद को call करने वाला एक function करता है।

उदाहरण: Parsing Nested Structures

php
<?php
// Define the function `countItems` taking `$tree`
function countItems($tree) {
    // Declare `$count`, set to `0`
    $count = 0;
    // Loop over `$tree`, binding each item to `$item`
    foreach ($tree as $item) {
        $count += is_array($item) ? countItems($item) : 1;
    }
    // Return `$count` from this function
    return $count;
}
// Print `countItems(["a", ["b", "c", ["d"]]])` to the output
echo countItems(["a", ["b", "c", ["d"]]]);
?>

Recursion बनाम Iteration

किसी भी recursive solution को एक loop इस्तेमाल करके iterative में फिर से लिखा जा सकता है, और iteration आमतौर पर तेज़ है और कम memory इस्तेमाल करता है, क्योंकि हर recursive call call stack में एक नया frame add करता है।

Recursion naturally self-similar problems के लिए *readability* पर जीतता है, भले ही यह raw performance पर हार जाए।

उदाहरण: Recursion vs Iteration

php
<?php
// Define the function `factorialRecursive` taking `$n`
function factorialRecursive($n) {
    // Return `$n <= 1 ? 1 : $n * factorialRecursive($n - 1)` from this function
    return $n <= 1 ? 1 : $n * factorialRecursive($n - 1);
}
// Define the function `factorialIterative` taking `$n`
function factorialIterative($n) {
    // Declare `$result`, set to `1`
    $result = 1;
    // Classic for-loop: `$i = 2; $i <= $n; $i++`
    for ($i = 2; $i <= $n; $i++) {
        $result *= $i;
    }
    // Return `$result` from this function
    return $result;
}
// Print `factorialRecursive(5) . " " . factorialIterative(5)` to the output
echo factorialRecursive(5) . " " . factorialIterative(5);
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. base case भूल जाना, ताकि function हमेशा के लिए खुद को call करता रहे जब तक PHP की memory या stack खत्म न हो जाए।
  2. argument को base case की ओर move न करना, जैसे factorial($n - 1) के बजाय factorial($n) call करना।
  3. बड़े inputs के लिए naive recursion इस्तेमाल करना, जैसे 40 का Fibonacci, जो same काम को exponentially दोहराता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.