PHP recursive function not returning expected -
i have 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 greater 0 returns 1 instead of 2 or 3.. how can make return other numbers?
you missing return keyword in order achieve recursion, otherwise function hasmoreparent
executed, flow continue , reach 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; }
Comments
Post a Comment