Pyramid Code in PHP?

I want to know the difference here with the two codes: The first one is short but the same output came with the second code, I only see the design difference.

for ($i=5;$i>=1;$i–){
echo str_repeat(“*”, “$i”);
echo ‘
’;
}

echo “


”;

for($i=0;$i<=5;$i++){
for($j=5-$i;$j>=1;$j–){
echo "* ";
}
echo “
”;
}

Output:

http://image.prntscr.com/image/51ff5ad9b89b404b96622d729a464660.png

you can code that even without a loop:

$arr = array_map(function ($num) {
    return str_repeat('*', $num);
}, range(1, 5));

echo implode(PHP_EOL, array_reverse($arr));
2 Likes

The only difference is that one block uses a short cut for the loop that the other doesn’t use.

str_repeat repeats a string by the number of times specified

So, this line

echo str_repeat("*", "$i");

does almost the same thing as this block of code (I say almost because the values echoed aren’t the same),

for($j=5-$i;$j>=1;$j--){
   echo "* ";
}

The difference is the str_repeat does it all at once where the loop will do it one block at a time…

1 Like

Right, so I should go with natural way of looping instead of shortcut str_repeat?

Didn’t say that - in this case, it’s two approaches to solve the same problem.

If all you want to do is repeat the same text X number of times, then str_repeat is the perfect vehicle to use. If, however, you would want to repeat the text X number of times, but change every 3rd character to a number and every 8th character to an exclamation point, and every 2nd letter out of every 10th group of 20 characters, then str_replace may not be the best approach. At that time, a separate loop would be more appropriate because it can give you more granular control.

Use the best tool (or block of code) for the right situation…

4 Likes

Understood… Thanks for the explanation :smiley:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.