How to Repeat a String in PHP Using str_repeat

In PHP, repeating a string multiple times is a common task easily achieved using the built-in str_repeat() function. This guide provides a quick and clear overview of how the str_repeat() function works, its syntax, parameter requirements, and practical code examples to help you implement it in your projects.

Understanding the str_repeat() Syntax

The str_repeat() function takes two arguments: the string you want to repeat, and the number of times you want to repeat it.

Here is the basic syntax:

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

Parameters

Return Value

The function returns the newly constructed string containing the repeated input.


Practical Examples

1. Basic String Repetition

To repeat a simple character or word a specific number of times, pass the string and the multiplier to the function.

<?php
echo str_repeat("-", 10);
// Output: ----------

echo str_repeat("Hello! ", 3);
// Output: Hello! Hello! Hello! 
?>

2. Creating Visual Separators or Padding

str_repeat() is highly useful for generating text-based visual dividers, such as dashes, underscores, or spaces in command-line outputs or text files.

<?php
$title = "REPORT SUMMARY";
echo $title . "\n";
echo str_repeat("=", strlen($title)) . "\n";

/* Output:
REPORT SUMMARY
==============
*/
?>

3. Handling Edge Cases: 0 and Negative Numbers

<?php
// Output is empty
echo str_repeat("test", 0); 

try {
    // This will throw a ValueError in PHP 8.0+
    echo str_repeat("test", -1);
} catch (ValueError $e) {
    echo "Error: " . $e->getMessage();
}
?>