str_repeat(): Repeat a String

Repeat a string

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.
$$$$$$$$$$

Syntax

str_repeat(string $string, int $times): string
ParameterDESCRIPTION
$stringRequired : Input string which is to be repeated
$multiplierRequired: Non-negative integer. Zero returns an empty string; negative values throw a ValueError in PHP 8+.
Using str_repeat string function we can repeat a string by a number ( known as multiplier ).

This loop increases the repetition count from 1 to 10:

*
**
***
****
*****
******
*******
********
*********
**********

Here is the code for this
for($i=1;$i<=10;$i++){
echo str_repeat("*",$i);
echo "<br>";
}

Example: Repeat String with Custom Separator

$separator = str_repeat('-=', 5);
echo $separator;  // Output: -=-=-=-=-=-=

Example: Creating a Line Divider

$divider = str_repeat('-', 50);
echo $divider;  // Output: --------------------------------------------------

Example: Adding a Fixed Number of Spaces

$str = 'Hello';
$padded_str = str_repeat(' ', 10) . $str;
echo $padded_str;  // Output: "          Hello"

Example: Building a Simple Progress Bar

$progress = 7;  // Progress out of 10
$bar = str_repeat('=', $progress) . str_repeat('-', 10 - $progress);
echo "[$bar]";  // Output: [=======---]

Example: Generating Fixed HTML List Items

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>

Example: Repeating a Fixed Pattern (Not for Passwords)

Repeated predictable sequences are not secure passwords. This is a string-repetition example only.

$pattern = str_repeat('ab1!', 3);
echo $pattern; // ab1!ab1!ab1!

String Functions str_pad(): Padding string nl2br() To add Line break


Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer