Search code examples
phpcodeignitercontrollermerging-data

passing variable from controller to view with CodeIgniter


I'm trying to structure my controllers in several small functions and I'm struggling with the following code:

building controller:

public function index(){
   $data['title'] = 'my title part 1';
   $data['title'] .= 'my title part 2';
   $data = $this->function1();
   $data = $this->function2();
   $data['end'] .= 'end of this block';
   $data['main_content'] = 'buildingView';
   $this->load->view('templates/default',$data); 
}

public function1(){
        $data['block1'] = 'test1';
        $data['blockA'] = 'testA';
        $data['blockB'] = 'testB';
        $data['blockC'] = 'testC';
        return $data;
}

public function2(){
        $data['block2'] = 'test2';
        $data['block3'] = 'test3';
        $data['block4'] = 'test4';
        $data['block5'] = 'test5';
        return $data;
}

buildingView

echo $title;
echo $block1;
echo $block2;
echo $end;

The problem is that the $data variable from function2 overwrites the one from from function1. How can I pass the data generated from within Index and both functions?

I've tried the code below but it doesn't work either:

$data[] = $this->function1();
$data[] = $this->function2();

EDIT: I edited functions 1 & 2 because they actually return an array of several variables.


Solution

  • You are overriding $data variable. So for your condition use array_merge() and keep it on top in $data variable. Like below

    public function index(){
       $data1 = $this->function1();
       $data2 = $this->function2();
       $data = array_merge($data1,$data2);
       $data['title'] = 'my title part 1';
       $data['title2'] .= 'my title part 2';
       $data['end'] .= 'end of this block';
       $data['main_content'] = 'buildingView';
       $this->load->view('templates/default',$data); 
    }
    
    public function1(){
            $data['block1'] = 'test1';
            $data['blockA'] = 'testA';
            $data['blockB'] = 'testB';
            $data['blockC'] = 'testC';
            return $data;
    }
    
    public function2(){
            $data['block2'] = 'test2';
            $data['block3'] = 'test3';
            $data['block4'] = 'test4';
            $data['block5'] = 'test5';
            return $data;
    }