1
votes

Im learning CodeIgniter and trying to follow best practices.

I was wondering where is the best place to execute a foreach loop?

Lets say I have a Model where I query the database and return all the results.

Then should I execute foreach in the Controller? Or rather View? Why?

1
It depends on your scenario. If you want to display the results to user then Model -> send results to, Controller -> View -> your foreach($withResults) loop. - Rahil Wazir
Yes, but I can also do the foreach loop in the controller and still pass results to the view. - C-Designer

1 Answers

2
votes

It depends what you're trying to do. If you're looping through results and outputting HTML, then I would recommend you do that in the view. If you're looping through results to do something to your data then outputting that to the view, then that logic would belong in the controller (or model).

I try to keep my views as PHP-free as possible, so when I have to loop through I tend to use alternate syntax for the loop. Here's an example:

<?php foreach ($x as $y) : ?>
<div>
    <h2><?php echo $y['title']; ?></h2>
    <p><?php echo $y['content']; ?></p>
</div>
<?php endforeach; ?>

The above ensures that should someone that only knows frontend development need to tweak the view, it's very clear what's happening there.