|
Posted by Steve on 04/12/07 13:25
"Rienk Withaar" <r.g.withaar@rug.nl> wrote in message
news:evl3nn$abq$1@info.service.rug.nl...
| Hello, I have the following problem:
|
| I want my function to return a value, $l, using the following function:
|
| function level($n,$l=0,$d=false) {
| if ($d) { return $l; }
| else {
| $ff=get_folders();
| for ($i=0;$i<count($ff);$i++) {
| if ($n==$ff[$i][0]) {
| if ($ff[$i][4]!=0) {
| $l++;
| level($ff[$i][4],$l,$d);
| }
| else {
| $d=true;
| level($ff[$i][0],$l,$d);
| }
| }
| }
| }
| }
|
| The function does not return $l, however. If I replace "return $l" in
| the first line of the function with "print $l", the right value for $l
| appears on the screen.
|
| Does anyone know a solution to this problem?
you could do with a much smaller 'nest'...
function level($n, $l = 0, $d = false)
{
if ($d){ return $l; }
// no need to have an else here
// get_folders();
// loop
// no need to have if nest here...
// if (!condition){ continue; }
// will suffice.
// no need at all for $d since
// you call the function again needlessly
// just so you can return $l from the
// previous iteration
}
i'll get to your answer shortly...there are more important things going on
here.
there are too many needless brackets and none of them are aligned. couple
that with meaningless variable names, and you've got the making of code that
is hard to debug and maintain. hmmm, that may lead to a post in a usenet
group. ;^)
consider this:
function level($n, $l = 0)
{
$ff = get_folders();
for ($i = 0; $i < count($ff); $i++)
{
if ($n != $ff[$i][0]){ continue; }
if ($ff[$i][4] != 0)
{
$l++;
level($ff[$i][4], $l);
} else {
return $l;
}
}
}
at least now you're dealing with meaningless variable names...but you can
read the code easier.
i assume get_folders() returns the same set of folders on each call to
level(). this code is going to run like a dog if that's the case. it looks
like you're screening with level() just so that you know where to begin
working/processing...VERY inefficient.
to answer your problem specifically, level NEVER ASSIGNS the return value to
ANYTHING in ANY ITERATION. it's just not thought out or executed well. state
what you're trying to do and i'll help you do it...correctly.
[Back to original message]
|