I think this is the work for template engine - but don`t worry, is pretty easy to use.
Only thing you need is prepared project with composer and after that easily install one of the template engine (for this example I picked up Latté).
Install of composer:
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
after that installing Latté:
php composer.phar require latte/latte
And on the end, you can create something like this:
$latte = new \Latte\Engine;
$latte->setTempDirectory('/path/to/tempdir');
$parameters['val'] = 2;
$html = $latte->renderToString('template.latte', $parameters);
and put this content into file "template.latte" in same directory:
<select>
{foreach [1, 2, 3] as $key}
<option {if $val === $key}>Option {$key}</option>
{/foreach}
</select>
This solution is used by professionals for many reasons:
- put logic and rendering side by side, does not mixed things up.
- All variables are automatically escaped (to avoid XSS)
- DRY (Do not Repeat Yourself) principe, that row with option should be written only once
BTW you always should use triple equals in condition in PHP (compares also type of variable). Its much more safe and you can save a lot of time of debug using this principle :-).