2

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?

2
  • 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. Commented Mar 2, 2014 at 21:55
  • Yes, but I can also do the foreach loop in the controller and still pass results to the view. Commented Mar 2, 2014 at 22:34

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.