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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -