www.webdeveloper.com
Results 1 to 3 of 3

Thread: Recursive Function returning emptry string

  1. #1
    Join Date
    Apr 2010
    Posts
    20

    Recursive Function returning emptry string

    I have a recursive function that mysteriously returns an empty string.

    I'm completely flummoxed by this behavior. In trying to debug, I have the function echo the function name and its arguments. I also have the function return a value upon termination and I echo this as well. One might think that there is an error in the function, but I even echo the string I'm going to return right before the return statement and I get the desired value, but somehow this value disappears when the function returns.

    Since this involves some SQL queries, I'm omitting the actual code but here is the gist of the function and its output in psuedocode.

    Code:
    <?php
    function Recur($name, $id)
    {	//actual code
    	echo 'Recur('.$name.','.$id.')<br>';
    	if($id == 0)
    		return $name;
    	//end comment
    	//pseudo code
    	else{
    	//do something
    		Recur($tmpname, $id-1);
    	}
            //end comment
    }
    
    	$result = Recur($name, $id);
    	echo $result;
    ?>
    Here is actual output:

    Recur(Updated Account, 0)
    Updated Account
    Recur(TestAccount1, 1)
    Recur(Updated Account:TestAccount1, 0)

    Recur(Test Account3, 0)
    Test Account3
    When I remove the echo $result line and insert echo $name before return $name, I get the same output as above, but the blank line is replaced with Updated Account:TestAccount1 as expected.

    Has anyone seen this behavior before?

    I might just give up and write a while loop. Oh PHP you disappoint me!
    Last edited by hattreid; 05-13-2010 at 02:12 AM.

  2. #2
    Join Date
    Aug 2009
    Posts
    593
    From what I can see...

    Quote Originally Posted by hattreid View Post
    Code:
    <?php
    function Recur($name, $id)
    {	//actual code
    	echo 'Recur('.$name.','.$id.')<br>';
    	if($id == 0)
    		return $name;
    		YOU WILL BE RETURNING A VALUE HERE
    	//end comment
    	//pseudo code
    	else{
    	//do something
    		return Recur($tmpname, $id-1);
    		YOU RECURS BUT RETURN NOTHING
    	}
            //end comment
    	NOTHING IS RETURNED BY DEFAULT
    }
    
    	$result = Recur($name, $id);
    	echo $result;
    ?>

  3. #3
    Join Date
    Apr 2010
    Posts
    20

    Solved

    Thank you. That was the solution.

    Strange, I had used recursion one other time so I wasn't aware this was necessary, but as I look at that other recursive function, it never returned a value. But thanks again for your eagle eyes.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles