PHP str_repeat() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
String

Definition

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.

Syntax

Call str_repeat() with the values you need. Start with this line.

PHP
$line = str_repeat("=", 20);
CallWhat 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.

Library declarations
PHP
str_repeat(string $string, int $times): string

Parameters

ParameterDescription
stringRequired. The string to repeat.
timesRequired. How many times to repeat it. Must be 0 or greater.

Return Value

Return ValueDescription
stringThe repeated string. Returns an empty string if times is 0.

PHP Examples

Example 1 — Repeat a Short String

Repeat two letters three times.

PHP
<?php
echo str_repeat("ab", 3), PHP_EOL;

How It Works

  1. Pass the text "ab".
  2. Pass the number 3 as the repeat count.
  3. PHP joins three copies together.
  4. The result is "ababab".

Example 2 — Repeat Zero Times

A count of 0 gives an empty string.

PHP
<?php
echo "[" . str_repeat("x", 0) . "]", PHP_EOL;

How It Works

  1. Ask for zero copies of "x".
  2. str_repeat returns an empty string.
  3. The square brackets show that nothing is inside.
  4. This is safe, but a negative count would throw an error.

Example 3 — Draw a Divider Line

A common use: print a line under a title.

PHP
<?php
$title = "Report";

echo $title, PHP_EOL;
echo str_repeat("=", 20), PHP_EOL;

How It Works

  1. Print the title first.
  2. Repeat the "=" character 20 times.
  3. PHP builds a single line of 20 equals signs.
  4. Print it below the title as a divider.

Frequently Asked Questions

str_repeat() repeats a string a number of times and returns the joined result. For example, str_repeat('ab', 3) returns 'ababab'.
You get an empty string. This is useful when the count is calculated and can sometimes be zero.
PHP 8 throws a ValueError. Make sure the repeat count is 0 or greater.
Use str_repeat('-', 30). Change the number to set the length of the line.
No. str_repeat() repeats a whole string. str_pad() adds characters to reach a target length.

Next: str_replace()

str_replace() replaces all occurrences of a search value with a replacement value in a str.

str_replace() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful