Dynamic views , according to certain parameters, is a challenge in any language.
There are basically three main approaches to dealing with this:
Scripts
The approach of mixing scripts with HTML is the most efficient one, but can easily lead to code that is difficult to understand, maintenance-prone and error-prone.
Template Engines
Using a templates engine helps separate logic from presentation. The side effect is performance, since templates need to be interpreted to generate the output.
Some mechanisms allow templates to "compile" to solve the performance problem, but this will require extra care in implementation.
I particularly like the templates approach.
Components
Some frameworks generate views through components, which are actually a collection of objects that encapsulate the generated HTML.
In PHP this is not as common as in Java, for example, but if I remember well Yii works that way.
The advantage is that there is a somewhat degree of reuse of code, but because of the great abstraction and complexity you can easily lose control of what you are doing, as well as render tasks that once were trivial in something that depends on a relative knowledge depth of the framework.
Considerations
There is no problem in using some ifs
or loops in the code, as long as you can separate it from the system logic.
A very simple example of how to use the PHP language itself as a type of template , thus avoiding the large number of classes included when using frameworks, can be seen in some templates of Wordpress. Example:
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<!-- do stuff ... -->
<?php endwhile; ?>
<?php endif; ?>