PHP Reference ยท String Functions
PHP str_repeat() function
Reference for PHP str_repeat(): repeat a string a given number of times, handle zero and negative counts, and build separators, indents and text bars.
str_repeat() returns a string made of the input repeated a given number of times. It is the usual way to draw separator lines, build indentation, or create padding of a computed width.
A multiplier of 0 gives an empty string. A negative multiplier is an error.
<?php echo str_repeat("=", 10); // ========== echo str_repeat("ab", 3); // ababab
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
str_repeat(string $string, int $times): string
| Name | Description |
|---|---|
$string |
The string to repeat. |
$times |
How many times to repeat it. Must be zero or greater. |
Return value: the repeated string. An empty input or 0 repeats gives "".
Errors: throws a ValueError if $times is less than 0 (PHP 8.0 and later).
Usage notes
- Memory. The result length is
strlen($string) * $times; a huge count can exhaustmemory_limit. Validate user-supplied counts. - No separator argument. For "repeat with a separator" combine
implode()witharray_fill(). - Padding. For padding to a fixed width,
str_pad()is simpler. - Multibyte-safe, since it simply copies bytes.
- Commonly used for text tables, ASCII bars and building indentation in code generators.