简体   繁体   中英

PHP repeat an HTML element without using loop

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM