W3docs

str_repeat()

Our article is about the PHP function str_repeat(), which is used to repeat a string a specified number of times. This function is useful when you need to

The PHP str_repeat() function returns a new string made by repeating a given string a specified number of times. It is handy for building repeated patterns such as separator lines, indentation, progress bars, or padding without writing the same characters over and over.

This chapter covers the syntax, parameters, return value, and the edge cases worth knowing, with runnable examples.

Syntax

str_repeat(string $string, int $times): string

Parameters

The function takes two required parameters:

  • $string — the string to repeat. It can be a single character or a longer string.
  • $times — how many times to repeat it. This must be 0 or greater.

Return value

str_repeat() returns the repeated string. If $times is 0, it returns an empty string (""). Passing a negative number raises a ValueError in PHP 8.0 and later (in earlier versions it triggered a warning and returned an empty string).

Basic example

php— editable, runs on the server

Here the string "Hello" is repeated three times, producing HelloHelloHello. Note that the parts are joined with no separator between them — str_repeat() simply concatenates the copies.

The output of this code will be:

HelloHelloHello

Practical uses

Drawing a separator line

A common use is generating a divider of a fixed width, instead of typing the same character dozens of times:

<?php
echo str_repeat("=", 20) . "\n";
echo "  Report\n";
echo str_repeat("=", 20) . "\n";
?>

Output:

====================
  Report
====================

Indentation and padding

Repeat spaces (or any string) to indent text by a level:

<?php
$level = 2;
$indent = str_repeat("    ", $level); // 4 spaces per level
echo $indent . "nested item\n";
?>

Output:

        nested item

If you only need to pad a string to a fixed total length (rather than repeat a fixed count), reach for str_pad() instead — it handles the width calculation for you.

Edge cases

  • Zero repetitions return an empty string:
<?php
var_dump(str_repeat("abc", 0)); // string(0) ""
?>
  • Repeating an empty string always yields an empty string, regardless of the count:
<?php
var_dump(str_repeat("", 5)); // string(0) ""
?>

Practice

Practice
What is the functionality of the 'str_repeat()' function in PHP?
What is the functionality of the 'str_repeat()' function in PHP?
Was this page helpful?