Skip to content
Tutorials Center
My learning

Topics

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
<?php
echo str_repeat("=", 10);   // ==========
echo str_repeat("ab", 3);   // ababab

Try it

PHP Lines, indents and bars

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.

PHP Invalid counts and joined repeats

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

PHP
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 exhaust memory_limit. Validate user-supplied counts.
  • No separator argument. For "repeat with a separator" combine implode() with array_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.