Passing variable from controller to view in CodeIgniter Passing variable from controller to view in CodeIgniter codeigniter codeigniter

Passing variable from controller to view in CodeIgniter


You have to pass an array to the view. CodeIgniter automatically makes $planet available to you.

$data = array('planet' => $planet);$this->load->view('main_view', $data);

With this you can use $planet in your view.

E.g., if you do the following:

$data = array('foo' => 'Hello', 'bar' => 'world');$this->load->view('main_view', $data);

$foo and $bar will be available in your view. The key-value pairs in the array are automatically converted to variables in the view.


You can pass either an array or an object to the view. You can then access the array key(s) as a variable(s) in your view.

Controller

Array

public function index(){    $this->load->model('main_model');    $planet_data['planet'] = $this->main_model->solar();    $this->load->view('main_view', $planet_data);}

Object

public function index(){    $this->load->model('main_model');    $planet_data = new stdClass(); //Creates a new empty object    $planet_data->planet = $this->main_model->solar();    $this->load->view('main_view', $planet_data);}

From CodeIgniter's user manual(deadlink): Note: If you use an object, the class variables will be turned into array elements.

View

Regardless of how you pass the data, it can be displayed like this:

<?php echo $planet; ?>

If it's an array then you would need to iterate through it. Or an object, then access it's member variables.


In my experience using an array is more common than using an object.


If modal contain array response:

public function solar() {   $data['earth'] = 'Earth';   $data['venus'] = 'Venus';   return $data;}

then you the data to view like this:

public function index(){    $this->load->model('main_model');    $planet = $this->main_model->solar();    $this->load->view('main_view', $planet);    }

But at view you will have access data like this:

echo $earth;echo $venus;

if you don't know want response will come then use code like this:

public function index(){    $this->load->model('main_model');    $planet['planet'] = $this->main_model->solar();    $this->load->view('main_view', $planet);    }

and in view file you can access the data like this:

print_r($planet);

If you don't know what data will come into view then just use this code at view:

print_r($this->_ci_cached_vars);