How to pass two arrays to view in codeigniter?

Member

by lily , in category: PHP Frameworks , 6 months ago

How to pass two arrays to view in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 6 months ago

@lily 

In CodeIgniter, you can pass two arrays to a view by combining them into a single array and then passing that array to the view. Here's how you can do it:


Controller:

1
2
3
4
5
6
7
8
public function index() {
    $data1 = array('foo' => 'bar', 'hello' => 'world');
    $data2 = array('name' => 'John Doe', 'email' => '[email protected]');

    $combined_data = array('data1' => $data1, 'data2' => $data2);

    $this->load->view('your_view', $combined_data);
}


View (your_view.php):

1
2
<p><?php echo $data1['foo']; ?></p>
<p><?php echo $data2['name']; ?></p>


In the above example, we first create two arrays $data1 and $data2 in the controller. We then combine these arrays into a single array $combined_data and pass it to the view using the load->view() method.


In the view, we can access the individual elements of the arrays by using the keys 'data1' and 'data2'. This allows us to pass and access multiple arrays in a single view in CodeIgniter.