What in layman's terms is a Recursive Function using PHP

前端 未结 16 1130
庸人自扰
庸人自扰 2020-11-22 05:50

Can anyone please explain a recursive function to me in PHP (without using Fibonacci) in layman language and using examples? i was looking at an example but the Fibonacci to

相关标签:
16条回答
  • 2020-11-22 06:29

    Walking through a directory tree is a good example. You can do something similar to process an array. Here is a really simple recursive function that simply processes a string, a simple array of strings, or a nested array of strings of any depth, replacing instances of 'hello' with 'goodbye' in the string or the values of the array or any sub-array:

    function replaceHello($a) {
        if (! is_array($a)) {
            $a = str_replace('hello', 'goodbye', $a);
        } else {
            foreach($a as $key => $value) {
                $a[$key] = replaceHello($value);
            }
        }
        return $a
    }
    

    It knows when to quit because at some point, the "thing" it is processing is not an array. For example, if you call replaceHello('hello'), it will return 'goodbye'. If you send it an array of strings, though it will call itself once for every member of the array, then return the processed array.

    0 讨论(0)
  • 2020-11-22 06:30

    This is a very simple example of factorial with Recursion:

    Factorials are a very easy maths concept. They are written like 5! and this means 5 * 4 * 3 * 2 * 1. So 6! is 720 and 4! is 24.

    function factorial($number) { 
    
        if ($number < 2) { 
            return 1; 
        } else { 
            return ($number * factorial($number-1)); 
        } 
    }
    

    hope this is usefull for you. :)

    0 讨论(0)
  • 2020-11-22 06:32

    Recursion is an alternative to loops, it's quite seldom that they bring more clearness or elegance to your code. A good example was given by Progman's answer, if he wouldn't use recursion he would be forced to keep track in which directory he is currently (this is called state) recursions allows him to do the bookkeeping using the stack (the area where variables and return adress of a method are stored)

    The standard examples factorial and Fibonacci are not useful for understanding the concept because they're easy to replace by a loop.

    0 讨论(0)
  • 2020-11-22 06:33

    Its a function that calls itself. Its useful for walking certain data structures that repeat themselves, such as trees. An HTML DOM is a classic example.

    An example of a tree structure in javascript and a recursive function to 'walk' the tree.

        1
       / \
      2   3
         / \
        4   5
    

    --

    var tree = {
      id: 1,
      left: {
        id: 2,
        left: null,
        right: null
      },
      right: {
        id: 3,
        left: {
          id: 4,
          left: null,
          right: null
        },
        right: {
          id: 5,
          left: null,
          right: null
        }
      }
    };
    

    To walk the tree, we call the same function repeatedly, passing the child nodes of the current node to the same function. We then call the function again, first on the left node, and then on the right.

    In this example, we'll get the maximum depth of the tree

    var depth = 0;
    
    function walkTree(node, i) {
    
      //Increment our depth counter and check
      i++;
      if (i > depth) depth = i;
    
      //call this function again for each of the branch nodes (recursion!)
      if (node.left != null) walkTree(node.left, i);
      if (node.right != null) walkTree(node.right, i);
    
      //Decrement our depth counter before going back up the call stack
      i--;
    }
    

    Finally we call the function

    alert('Tree depth:' + walkTree(tree, 0));
    

    A great way of understanding recursion is to step through the code at runtime.

    0 讨论(0)
  • 2020-11-22 06:35

    Recursion is something that repeats itself. Like a function that calls itself from within itself. Let me demonstrate in a somewhat pseudo example:

    Imagine you're out with your buddies drinking beer, but your wife is going to give you hell if you don't come home before midnight. For this purpose, let's create the orderAndDrinkBeer($time) function where $time is midnight minus the time it takes you to finish your current drink and get home.

    So, arriving at the bar, you order your first beer and commence the drinking:

    $timeToGoHome = '23';  // Let's give ourselves an hour for last call and getting home
    
    function orderAndDrinkBeer($timeToGoHome) {  // Let's create the function that's going to call itself.
        $beer = New Beer();  // Let's grab ourselves a new beer
        $currentTime = date('G'); // Current hour in 24-hour format
    
        while ($beer->status != 'empty') {  // Time to commence the drinking loop
            $beer->drink();  // Take a sip or two of the beer(or chug if that's your preference)
        }
    
        // Now we're out of the drinking loop and ready for a new beer
    
        if ($currentTime < $timeToGoHome) { // BUT only if we got the time
            orderAndDrinkBeer($timeToGoHome);  // So we make the function call itself again!
        } else {  // Aw, snap!  It is time :S
            break; // Let's go home :(
        }
    }
    

    Now let's just hope you weren't able to drink enough beer to become so intoxicated that your wife is going to make you sleep on the couch regardless of being home on time -.-

    But yeah, that's pretty much how recursion goes.

    0 讨论(0)
  • 2020-11-22 06:35

    Recursion is a fancy way of saying "Do this thing again until its done".

    Two important things to have:

    1. A base case - You've got a goal to get to.
    2. A test - How to know if you've got to where you're going.

    Imagine a simple task: Sort a stack of books alphabetically. A simple process would be take the first two books, sort them. Now, here comes the recursive part: Are there more books? If so, do it again. The "do it again" is the recursion. The "are there any more books" is the test. And "no, no more books" is the base case.

    0 讨论(0)
提交回复
热议问题