What is the str_repeat method in PHP?

The str_repeat method returns a new string whose value is the concatenation of the argument string repeated n times, where n is passed as an argument.

Syntax


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

Arguments and return type

string: The string to be repeated.

n: An integer value representing the number of times the string needs to be repeated. n should be a positive value. If we pass 0, then an empty string will return.

Code

Example 1

<?php
echo "loading". str_repeat(".", 10);
?>

Explanation 1

In the code above, we call the str_repeat method with . as the value for the first argumentThe first argument denotes the string to be repeated. and 10 as the value for the second argumentThe second argument denotes the number of times the string is to be repeated. This will return a string in which . is repeated 10 times.

Example 2

<?php
echo str_repeat("^", 5);
echo("\n");
echo str_repeat("---", 0); // empty string will be returned
echo("\n");
echo str_repeat("$$$", 1);
echo("\n");
echo str_repeat("Test ", 3);
// echo str_repeat("Test ", -1); // n < 0 -> this will throw warning
?>

Free Resources