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): stringParameters
$string: The input string that you want to repeat.$times: The number of times the input string should be repeated. This value must be greater than or equal to0.
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
- Multiplier is
0: If you pass0as the$timesargument, the function returns an empty string (""). - Multiplier is Negative: In PHP 8.0 and later,
passing a negative number throws a
ValueError. In older PHP versions, it generates a warning and returns an empty string.
<?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();
}
?>