str_repeat() returns a string repeated the requested number of times. The multiplier must be zero or greater.
echo str_repeat('=', 10); // ==========
echo str_repeat('$',10);
The above command will print $ ten times.
$$$$$$$$$$
str_repeat(string $string, int $times): string
| Parameter | DESCRIPTION |
|---|---|
$string | Required : Input string which is to be repeated |
$multiplier | Required: Non-negative integer. Zero returns an empty string; negative values throw a ValueError in PHP 8+. |
for($i=1;$i<=10;$i++){
echo str_repeat("*",$i);
echo "<br>";
}
$separator = str_repeat('-=', 5);
echo $separator; // Output: -=-=-=-=-=-=
$divider = str_repeat('-', 50);
echo $divider; // Output: --------------------------------------------------
$str = 'Hello';
$padded_str = str_repeat(' ', 10) . $str;
echo $padded_str; // Output: " Hello"
$progress = 7; // Progress out of 10
$bar = str_repeat('=', $progress) . str_repeat('-', 10 - $progress);
echo "[$bar]"; // Output: [=======---]
This example generates trusted static markup. Escape dynamic list-item content before putting it into HTML.
$list_item = str_repeat('<li>Item</li>', 5);
echo "<ul>$list_item</ul>";
// Output: <ul><li>Item</li><li>Item</li><li>Item</li><li>Item</li><li>Item</li></ul>
Repeated predictable sequences are not secure passwords. This is a string-repetition example only.
$pattern = str_repeat('ab1!', 3);
echo $pattern; // ab1!ab1!ab1!
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.