What I think you need to realize is that the computer behind your PHP script can “remember” the values you create in your model or business logic. That is what variables in PHP are for! You then use your view to take any of the “remembered” data from the model/ business logic and render it in your HTML (template) files. You basically pass the data through the computer to the view, which is also manipulated according to your code and through the computer. In fact, this is what PHP’s core principle is and what it was meant to do from its inception. Add dynamic data to HTML.
Edit: I realize my reply might sound a bit, um…dumbed down, which isn’t my intention. But, I think somehow you are missing a fundamental understanding of what you can do with PHP and I realize my answer doesn’t point that out very well. The other gents here did a better job. What you might want to study is the MVC architecture pattern. https://en.wikipedia.org/wiki/Model–view–controller
You should distinguish business logic and view logic.
Business logic is “what to do to create/retrieve data” and view logic is “how to format that data for viewing”.
So the first one should be placed inside controller while second one goes to templates (views).
It’s absolutely OKAY to have loops and conditions inside your view file until they serve only for output purposes (building table rows, hiding or showing blocks etc).