str_repeat

Returns a string made of the input repeated a given number of times.

Signature
str_repeat(string $string, int $times): string
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$stringstringThe string to repeat.
$timesintHow many times to repeat the string. Must be greater than or equal to 0.

Return value

stringThe input string repeated times times. An empty string when times is 0.

Errors

Throws a ValueError if times is negative. A result larger than the string size limit raises a fatal error.

Changelog

  • PHP 8.0Passing a negative times now throws a ValueError; previously it emitted E_WARNING and returned false.

str_repeat concatenates a string with itself a fixed number of times. It is one of the simplest functions in the language and one of the most useful in output code.

When to reach for it

Use it for separators and rules in CLI output (str_repeat('-', 60)), indentation when pretty-printing nested data (str_repeat(' ', $depth)), text progress bars and simple charts, and placeholder lists for prepared statements. It is also the fastest way to build a large test string of a known size when benchmarking.

What trips people up

A negative count throws a ValueError in PHP 8 rather than warning and returning false, so a computed count like $width - strlen($label) needs a max(0, ...) guard when the label can be longer than the width. Zero is fine and yields an empty string.

Memory is the other trap: the result is materialised in full, so str_repeat($s, $n) allocates strlen($s) * $n bytes. A count derived from user input can exhaust the memory limit. And because it counts repetitions rather than bytes, repeating a multibyte character is safe — unlike str_pad, no character is ever split.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Draw a separator line of an exact width in CLI output
  • Indent nested output by depth when pretty-printing a tree
  • Build a comma-separated list of SQL placeholders for a prepared statement
  • Render a simple text progress or rating bar

Frequently asked questions

What happens if I pass a negative count to str_repeat?

It throws a ValueError in PHP 8 and later. Before PHP 8 it emitted a warning and returned false, so code that relied on that behaviour needs a max(0, ...) guard.

What is the difference between str_repeat and str_pad?

str_repeat repeats a string a fixed number of times regardless of the result length; str_pad grows a string until it reaches a target length. Use str_pad when you care about the final width, str_repeat when you care about the repetition count.

Is str_repeat safe with UTF-8 characters?

Yes. It repeats the whole byte sequence you give it, so multibyte characters are never split. Only length-based functions such as str_pad have the byte-counting problem.

More examples

SQL placeholders and safe counts

The first part builds "?,?,?,?" and trims the trailing comma, the standard way to size an IN clause for a prepared statement. The second part shows the guard: the label is longer than the target width, so the subtraction is negative and max(0, ...) is what stops str_repeat from throwing a ValueError.

Example · php
<?php
$ids = [7, 12, 19, 44];

$placeholders = rtrim(str_repeat('?,', count($ids)), ',');
echo "SELECT * FROM users WHERE id IN ({$placeholders})\n";

$label = 'Total';
$width = 3;
echo '[', $label, str_repeat(' ', max(0, $width - strlen($label))), "]\n";

A text progress bar

Each row shows the filled and empty halves adding up to exactly 20 characters, because the two counts are derived from the same width. The 0% and 100% rows confirm that a repeat count of zero is legal and simply produces an empty string.

Example · php
<?php
function bar(int $percent, int $width = 20): string {
    $done = (int) round($width * $percent / 100);
    return '[' . str_repeat('#', $done) . str_repeat('.', $width - $done) . '] ' . $percent . '%';
}

foreach ([0, 35, 70, 100] as $p) {
    echo bar($p), "\n";
}

Discussion

  • Be the first to comment on this lesson.