How to pass an array to the main view in codeigniter?

Member

by rollin , in category: PHP Frameworks , a year ago

How to pass an array to the main view in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , a year ago

@rollin 

To pass an array to the main view in CodeIgniter, you can use the second parameter of the load->view() method.

  1. In your controller, create an array that you want to pass to the view. For example:
1
2
3
4
5
$data = array(
    'name' => 'John Doe',
    'age' => 30,
    'country' => 'USA'
);


  1. Load the view and pass the array as the second parameter. For example:
1
$this->load->view('main_view', $data);


Here, main_view is the name of your view file.

  1. In your main view file (main_view.php), you can access the passed array using the same keys. For example:
1
2
3
<p>Name: <?php echo $name; ?></p>
<p>Age: <?php echo $age; ?></p>
<p>Country: <?php echo $country; ?></p>


Here, you can simply access the array values using the corresponding keys ('$name', '$age', and '$country').


Note: Make sure you have already loaded the 'view' library in your controller, either in the constructor or using the $this->load->library('view') method.

Related Threads:

How to pass two arrays to view in codeigniter?
How to pass data from a controller to a view in Phalcon?
How to pass controller data to view in laravel?
How to pass multiple models to laravel view?
How to get the data from view in codeigniter?
How to access to another view in codeigniter?