How to use foreach in codeigniter?

Member

by gilbert , in category: PHP Frameworks , 8 months ago

How to use foreach in codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 8 months ago

@gilbert 

In CodeIgniter, you can use the foreach loop to iterate over an array or object in your views or controllers.


Here is an example of how to use foreach in a CodeIgniter view:

1
2
3
4
5
<ul>
<?php foreach($items as $item): ?>
    <li><?php echo $item; ?></li>
<?php endforeach; ?>
</ul>


In this example, we have an array or object called $items with multiple items. We use the foreach loop to iterate over each item and display it in an HTML list.


You can also use foreach in CodeIgniter controllers to iterate over data fetched from a database or other sources. Here is an example:

1
2
3
4
5
6
public function index()
{
    $data['items'] = $this->db->get('items')->result();
    
    $this->load->view('items_view', $data);
}


In this controller method, we fetch a collection of items from the database and pass it to the view. In the corresponding view, we use the foreach loop to iterate over the items and display them.


Overall, foreach is a powerful tool in CodeIgniter for iterating over arrays or objects and displaying data in views or controllers.