Foreach loop in views in Codeigniter

The data array you pass to your view files is not limited to simple variables. You can pass multi dimensional arrays, which can be looped to generate multiple rows.

Controller file (Hello.php)

<?php
class Hello extends CI_Controller {
	public function index()
	{
		$rawArray = array(
				'fruits' => array('apple', 'banana','oranges','cherry'), // array within array
				'computer' => 'electronics',
				'wheat' => 'grains'
		);

		$this->load->view("first", $rawArray);
	}
}

View file (first.php)

<html>
<head>
<title>demonstration of foreach</title>
</head>
<body>

	<?php

	echo $computer . "<br>";
	echo $wheat . "<br>";
	?>
	<!-- array within array loop -->

	<ul>
		<?php foreach ($fruits as $item):?>
		<li><?php echo $item;?>
		</li>
		<?php endforeach;?>
	</ul>

</body>
</html>

Output

Untitled

Share

You may also like...