1

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?

4
  • You can use str_repeat Commented Mar 10, 2017 at 21:19
  • 4
    "over-optimizing fun!" The simple for loop is probably faster than your fancy one-liner. Commented Mar 10, 2017 at 21:19
  • 2
    Any way you do this will probably involve a loop at some point in the code, potentially behind the scenes, so I don't know if this would be optimizing. Commented Mar 10, 2017 at 21:19
  • 2
    "is there a simpler way?" - Simpler than... a loop? If you want to repeat an action until a condition is met, that's exactly what a loop is for. You're likely saving nothing in optimization but costing time in obtuse code. Even if you somehow manage to save a millisecond is processing time, it's going to require a lot of application volume to make up for all the development time spent creating and supporting "clever code". Commented Mar 10, 2017 at 21:24

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.