Example 1 — Repeat a Short String
Repeat two letters three times.
<?php
echo str_repeat("ab", 3), PHP_EOL; How It Works
- Pass the text "ab".
- Pass the number 3 as the repeat count.
- PHP joins three copies together.
- The result is "ababab".

In PHP, str_repeat() repeats a string a given number of times and returns the combined result.
It is perfect for drawing divider lines, indenting text, or creating padding.
Call str_repeat() with the values you need. Start with this line.
$line = str_repeat("=", 20); | Call | What it does |
|---|---|
str_repeat("ab", 3) | Returns "ababab". |
str_repeat("-", 10) | Returns "----------". |
str_repeat("x", 0) | Returns an empty string. |
The repeat count must be zero or more. A negative number throws a ValueError in PHP 8.
str_repeat(string $string, int $times): string | Parameter | Description |
|---|---|
| string | Required. The string to repeat. |
| times | Required. How many times to repeat it. Must be 0 or greater. |
| Return Value | Description |
|---|---|
| string | The repeated string. Returns an empty string if times is 0. |
Repeat two letters three times.
<?php
echo str_repeat("ab", 3), PHP_EOL; A count of 0 gives an empty string.
<?php
echo "[" . str_repeat("x", 0) . "]", PHP_EOL; A common use: print a line under a title.
<?php
$title = "Report";
echo $title, PHP_EOL;
echo str_repeat("=", 20), PHP_EOL; str_replace() replaces all occurrences of a search value with a replacement value in a str.
8 people found this page helpful