Nitish
Nitish

Reputation: 2763

Recursive function result as array not showing desired result

I have a controller ajax where the two functions exists :

  function customer_comission()
  {
            ---------------------------
            ---------------------------
        $arr = $this->show_parent_id( $child_node );

        var_dump($arr);
            ----------------------------
            ---------------
  }

function show_parent_id( $cust_id ){

    if( $cust_id > 2 ):
        $cust_id2 = $this->comission_model->show_parent_id( $cust_id );
        $cust_array[] = $cust_id2;
        //echo $this->show_parent_id( $cust_id2 ); 
         $this->show_parent_id( $cust_id2 );  
    endif;

    return $cust_array; // <-- This is Line 38
}

So what I want to display is the array of parent_id's for the $cust_id hierarchy. The echo $this->show_parent_id( $cust_id2 ); prints the desired results, but when I tried to add them in an array, and then I got the error is showing :

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: cust_array

Filename: controllers/ajax.php

Line Number: 38

Upvotes: 0

Views: 48

Answers (1)

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

That is because whenever $cust_id <= 2 then $cust_array variable falls undefined.So just initialize it befor the if condition like this

function show_parent_id( $cust_id ){
    $cust_array = array();
    if( $cust_id > 2 ){
        $cust_id2 = $this->comission_model->show_parent_id( $cust_id );
        $cust_array[] = $cust_id2;
        //echo $this->show_parent_id( $cust_id2 ); 
         $this->show_parent_id( $cust_id2 );  
    }

    return $cust_array; // <-- This is Line 38
}

Upvotes: 1

Related Questions