1

I have the following code:

use app\models\Kategorije;

function hasMoreParent($id,$i = 0){
    $model = new Kategorije();
    $parent_id = $model::find()->where('id = :id',[':id' => $id])->one()->parent_id;
    if ($parent_id > 1) {
        $i++;
        hasMoreParent($parent_id,$i);
    }
        return $i;
}

And, if $i is greater than 0 it always returns 1 instead of 2 or 3.. How can I make it to return those other numbers?

user3002173
  • 135
  • 1
  • 8
  • you never capture the return values of the recursive calls, so at the top-level, you'll only ever get the FIRST call's value returned. you probably want `$i += hasMoreParent(...)` instead. – Marc B Sep 29 '15 at 21:32
  • Can you write the example @MarcB ? – user3002173 Sep 29 '15 at 21:36

1 Answers1

0

You are missing the return keyword in order to achieve the recursion, otherwise the function hasMoreParent will be executed, but the flow will continue and reach the return $i; statement.

use app\models\Kategorije;

function hasMoreParent($id, $i = 0) {
    $model = new Kategorije();
    $parent_id = $model::find()->where('id = :id', [':id' = > $id])->one()->parent_id;
    if ($parent_id > 1) {
        $i++;
        return hasMoreParent($parent_id, $i);
    }
    return $i;
}
taxicala
  • 21,408
  • 7
  • 37
  • 66