将html存储到变量中的优缺点

Is there any advantage (in terms of speed) of using the first method before the second?

Is this

foreach ($variable as $key => $value) {
    $items .= '<li>'.$value.'</li>';
}
echo '<ul>'.$items.'</ul>'

faster than this?

<ul>
<?php foreach ($variable as $key => $value): ?>
    <li><?php echo $value; ?></li>;
<?php endforeach ?>
</ul>

Have no doubt that second is more faster than first one cuz first have one more process( inputting to $items) while second is directly printing the value. Here you can check more about php code optimization.

https://kinsta.com/blog/10-things-not-to-do-in-php-7/

https://kinsta.com/learn/page-speed/

Pros:

  • Easy for developer to pass data to front end without any framework or templating engine.
  • No much handling needed in case of data is no there as no html code will be displayed.
  • Ok for beginners or small applications or website

Cons:

  • Not Good for Big Application
  • Framework or templating engine needed to handle data at front end
  • designer is free to design any kind of theme and developer doesn't have to know much of designing part
  • Easy to change UI in future without disrupting your working
  • Designer will never mess with your php codes as they are separate and will algo will never change accidentally.
  • Handling HTML code when no data appears from back-end

There are lot more and choice differ from person to person what to use and what to not. But I personally hate when php codes and HTML codes are mixed together.

<ul>
<?php foreach ($variable as $key => $value): ?>
    <li><?php echo $value; ?></li>;
<?php endforeach ?>
</ul>

This is the faster option as we are not using a variable in this thats why server response time will be increase and it will be faster... :)

No your first code is less faster than the second code because when you run first code it will reserve memory $item. if you will run loop 10 times it will increase the memory of variable. that effects the speed of your code. in second code there is no extra memory utilization so it will work more fast than the first code because memory consumption is less.