Question

What is the faster way to output html in PHP that contains PHP variables?

Version A:

<div id="example"><?php echo $var; ?></div>
... much more like this

or

Version B:

$html = array();

$html[] = '<div id ="example">';
$html[] = &$var;
$html[] = '</div>';
$html[] = '... much more like this';

echo implode( '', $html );
Was it helpful?

Solution 2

In this case it is faster to mix html and php. Version B, will essentially hold a big array in memory, and in the end loop through all the elements. So it will be slower, than just print/echo the data right away. Either way, I won't recommend either approach. I will suggest using a template engine and provide it with data, instead of mixing php and html, this way you can keep markup and logic completely separate. This is often done as a part of a MVC pattern as @Wrong described.

OTHER TIPS

PHP - Hypertext Pre Processor

In fact, PHP is a templating engine itself. In any case variant A is better, but such code isn't the best solution for bigger projects. Try looking on MVC design pattern, which will help you separate database/business logic from the representation part of your application. Using an template engine (like Twig, Smarty, Blitz etc.) will help you achieve this too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top