PDA

View Full Version : Recursive Kinda Working

dniwebdesign
05-08-2006, 05:17 AM
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?

ralph l mayo
05-08-2006, 05:29 AM
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:

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

dniwebdesign
05-08-2006, 05:41 AM
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.