store Recursive function value in array (php) -


i have function find parent of child have created function m getting parent id not able save in 1 array , return 1 array instead last valu getting inserted . array_push not working in case here.

function has_parent($parent,$con) {     $return  = array();          $selectparent = "select * table id = $parent ";         $qresult = mysqli_query($conobj,$selectparent);         $qrow = mysqli_fetch_assoc($qresult);         $parent_id = $qrow['parent_id'];         if ($parent_id != 0) {             //$return[] = $parent_id;             echo $parent_id; // geting parent id 432              $return[] = $parent_id;             $a = has_parent($parent_id, $con);         }else{             return $parent_id;         }      return $return; }  $marray =  folder_has_parent($parent ,$con); print_r($marray); // getting last array  array (     [0] => 4 ) 

expected output:

array (     [0] => 4     [1] => 3     [3] => 2 ) 

you overriding $return time when calling recursive function in line $return = array();. instead should try making $return global variable hence no longer in function scope.

function has_parent($parent,$con) {     global $return; // global variable     $selectparent = "select * table id = $parent ";     $qresult = mysqli_query($conobj,$selectparent);     $qrow = mysqli_fetch_assoc($qresult);     $parent_id = $qrow['parent_id'];     if ($parent_id != 0) {         //$return[] = $parent_id;         echo $parent_id; // geting parent id 432          $return[] = $parent_id;         $a = has_parent($parent_id, $con);     }else{         return $parent_id;     }      return $return; }  $return  = array(); // setting global variable $marray =  folder_has_parent($parent ,$con); print_r($marray); 

Comments