Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder dniwebdesign's Avatar
    Join Date
    Dec 2003
    Location
    Carrot River, Saskatchewan
    Posts
    845
    Thanks
    15
    Thanked 10 Times in 10 Posts

    Recursive Kinda Working

    PHP Code:
        function getDepth($id,$depth) {
            
    //global $connection;
            
    if($depth>10) {
                return 
    $depth;
            }
            else {
                
    $depth $depth+1;
                echo 
    $depth."<br>";
                
    $this->getDepth(0,$depth);
                
    // return $depth;
            
    }
        } 
    Alrighty, I have the above function, which right now should count to 11 then return the number (which should be 11). However although it does do the recursive and counts all the way to 11 it does not return the value once it is greater than 10. Why?
    Dawson Irvine
    CEO - DNI Web Design
    http://www.dniwebdesign.com

  • #2
    Regular Coder ralph l mayo's Avatar
    Join Date
    Nov 2005
    Posts
    951
    Thanks
    1
    Thanked 31 Times in 29 Posts
    Quote Originally Posted by dniwebdesign
    Alrighty, I have the above function, which right now should count to 11 then return the number (which should be 11). However although it does do the recursive and counts all the way to 11 it does not return the value once it is greater than 10. Why?

    If you want to use the return value of a recursive function it has to return itself instead of just calling itself.

    The way you've written it, the first call, with a depth <= 10, calls another recursion of getDepth but itself runs to completion without hitting a return. If you change that line to return $this->getDepth(0, $depth), though, it will create a chain of returns ending at the terminating condition.

    Simplified example:

    PHP Code:
    function getDepth_2($depth)
    {
        return (
    $depth 10) ? $depth getDepth_2(++$depth);
    }
    echo 
    getDepth_2(0); // 11 

  • #3
    Regular Coder dniwebdesign's Avatar
    Join Date
    Dec 2003
    Location
    Carrot River, Saskatchewan
    Posts
    845
    Thanks
    15
    Thanked 10 Times in 10 Posts
    Well,
    Make sense, however I am wanting this to use a mysql query as well... I need it to keep track of how far I am into a category from the root. Almost like a tree depth for example. How would I go about implementing this.
    Dawson Irvine
    CEO - DNI Web Design
    http://www.dniwebdesign.com


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •