PHP String str_repeat Function
The PHP String str_repeat() function is used to generate a new string by repeating a given string a specific amount of times. It accepts a string and an integer as inputs and returns a new string created by repeating the string given as an argument the number of times given by the integer provided as an argument to this function.
Syntax
Below is the syntax of the PHP String str_repeat() function −
string str_repeat ( string $string, int $times )
Parameters
Here are the parameters of the str_repeat() function −
$string − (Required) It is the string to be repeated.
$times − (Required) It is the number of times a string should be repeated. This parameter must be greater than or equal to zero. If the timestamp is set to zero, the method returns an empty string.
Return Value
The str_repeat() function returns a new string created by repeating the given string $string the specified number of times. If the function's parameter $no_of_times equals 0, it returns an empty string.
PHP Version
First introduced in core PHP 4, the str_repeat() function continues to function easily in PHP 5, PHP 7, and PHP 8.
Example 1
First we will show you the basic example of the PHP String str_repeat() function to repeat the given string five times.
<?php $string = "Tutorialspoint "; $times = 3; echo str_repeat( $string, $times ); ?>
Output
Here is the outcome of the following code −
Tutorialspoint Tutorialspoint Tutorialspoint
Example 2
In the below PHP code we will try to use the str_repeat() function and combine it with a loop to create a pattern.
<?php
for ($i = 1; $i <= 5; $i++) {
echo str_repeat("*", $i) . "\n";
}
?>
Output
This will generate the below output −
* ** *** **** *****
Example 3
Now the below code uses str_repeat() function with loops to create a pyramid pattern of ampersand (&).
<?php
$rows = 5;
for ($i = 1; $i <= $rows; $i++) {
// Create spaces for alignment
$spaces = str_repeat(" ", $rows - $i);
// Create stars for the current row
$stars = str_repeat("&", 2 * $i - 1);
// Print the row
echo $spaces . $stars . "\n";
}
?>
Output
This will create the below output −
&
&&&
&&&&&
&&&&&&&
&&&&&&&&&
Example 4
In the following example, we are using the str_repeat() function to modify a given string by repeating each character a number of times.
<?php
function repeatCharacters($string, $times) {
$result = "";
for ($i = 0; $i < strlen($string); $i++) {
// Repeat each character
$result .= str_repeat($string[$i], $times);
}
return $result;
}
// Example usage
$input = "ABC";
$times = 3;
echo repeatCharacters($input, $times);
?>
Output
Following is the output of the above code −
AAABBBCCC