doukuangxun5382 2017-03-10 21:17
浏览 11
已采纳

PHP重复HTML元素而不使用循环

This might be crazy, but I was thinking there might be a shorthand way to do this without using a loop on one php line... over-optimizing fun!

$stars = 4; // four out of ten stars

print stars with a loop

for($i=0;$i<$stars;$i++){
 echo "<i class='fi-star'></i>";
}

print without loop

<?=implode("",array_fill(0,$stars,"<i class='fi-star'></i>"))?>

is there a simpler way?

  • 写回答

1条回答 默认 最新

  • dsqe46004 2017-03-10 21:19
    关注

    Yes, you can use the str_repeat function.

    In your case, you can use it like this:

    echo str_repeat("<i class='fi-star'></i>", $stars);
    

    Note that this won't make your code any more efficient. It is just a shorthand way to do the same as what you are doing with the for loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)