Skip to content
Home » Web » PHP » How to Repeat String N Times

How to Repeat String N Times

Sometimes, we may want to indent the output presented on the browser by padding leading spaces. Furthermore, we want the indentation more elaborate according to their levels. For example:

  • Level 1: padding " "
  • Level 2: padding "  "
  • Level 3: padding "   "
  • ...
  • Level 100: what about this?

What about the padding string for level 100? Of course, you can do it manually, but it's not flexible for various numbers. Luckily, PHP provide a function str_repeat() which can concatenate a string multiple times. In the above case, we can do it like this:

<?php
$level = 100;
$padding = "&nbsp;";
$leadings = str_repeat("&nbsp;", $level);
echo $leadings . "We are on level " . $level;
?>

That is what we want. It's neat and robust.

Leave a Reply

Your email address will not be published. Required fields are marked *