PHP str_repeat: How it Works with Examples

php str_repeat function

PHP gives you many string tools. One of them is php str_repeat. This function repeats a texts as many times as you need. You can build patterns, repeat characters, or format output.

Understand the PHP str_repeat Function

You can use str_repeat() to duplicate a string multiple times. You give it two things: the text you want and how many times you want to repeat it. PHP puts them together and gives you one string back.

You write it like this:

str_repeat(string $input, int $multiplier)

You must pass a text and an integer. The string is what you want to repeat. The number tells PHP how many times to do that.

  • $input: the text you want to repeat. It can be one character or a full sentence.
  • $multiplier: how many times to repeat it. If this is 0 or less, PHP returns an empty string.

The return is one string. It contains your input repeated in a row.

Here is a quick example:

echo str_repeat("Hi ", 3);

The output:

Hi Hi Hi 

PHP repeats “Hi ” three times and joins it into one line.

You can repeat anything. Here are a few examples:

echo str_repeat("-", 10);  // ----------

echo str_repeat("ABC", 2); // ABCABC

echo str_repeat("0", 5);   // 00000

You can use this to build spaces or fillers. Or also repeat patterns.

PHP str_repeat Output formatting using str_repeat()

You can also use str_repeat() when you want a better layout or pattern control. It helps in output design or spacing.

You can repeat parts of a string and then pad it to a full length:

$credit_card = "5555666677775424";
$masked = str_repeat("*", 12) . substr($credit_card, -4);
echo $masked;

The output:

************5424

Let me also explain the logic:

  • str_repeat("*", 12) generates 12 asterisks.
  • substr($credit_card, -4) grabs the last 4 digits.
  • Combine both to mask the first 12 digits.

You can build a line from an array and repeat spaces:

$items = ["A", "B", "C"];
$gap = str_repeat(" ", 3);
echo implode($gap, $items);

The output:

 A   B   C

This joins items with three spaces between each.

Examples of str_repeat Function in PHP

You can use user input or loop counters to decide how many times to repeat:

$count = 4;
for ($i = 1; $i <= $count; $i++) {
    echo str_repeat("#", $i) . "\n";
}

This creates a step pattern:

#
##
###
####

You can use symbols, emojis, or non-English letters:

echo str_repeat("🔥", 3); // 🔥🔥🔥
echo str_repeat("ü", 4);  // üüüü

It handles UTF-8 strings without trouble.

You can repeat HTML tags or spaces to build templates:

echo "<ul>";
echo str_repeat("<li>Item</li>", 3);
echo "</ul>";

This creates three list items inside a <ul> block.

When you want fake rows or spacer lines in CLI or reports:

echo str_repeat("-", 50);
// Output: --------------------------------------------------

You can also use it to create placeholder strings or block letters in fake text.

Wrapping Up

In this article, you learned how to use php str_repeat in plain text and inside loops. You also saw how to combine it with implode, str_pad or HTML elements.

Here is a quick recap:

  • str_repeat() repeats a text based on a count.
  • It works with plain text and symbols with HTML.
  • You can use it with loops and arrays. And even user input.
  • It helps with output formatting and build patterns.

FAQs

What is the use of str_repeat in PHP?

You use str_repeat when you want to show the same string multiple times. It builds patterns, spacing, or repeated blocks. You can use it in HTML templates, console output, or data formatting.

What happens if I give a negative number?

PHP returns an empty string. It does not show any error.

Can I repeat Unicode or emoji?

Yes. PHP handles them fine. You can repeat any valid string.

Can I use it with user input?

Yes. Just make sure the input is safe and the repeat count is a number.

Similar Reads

PHP Named Arguments vs. Positional Arguments

The PHP named arguments are the names of the arguments through which the values are passed, allowing you to add…

PHP filter_var: Understand How to Sanitize Input

PHP didn’t have a way to check or clean user input. Developers used scattered code—some wrote custom checks, others used…

PHP array_diff_key Function: How it Works with Examples

PHP array_diff_key compares arrays and removes elements that share the same key. It checks only keys and keeps the values…

PHP Null Coalescing Operator: Handling Null Values

The PHP null coalescing operator, written as ??, is a helpful feature added in PHP 7. It makes it easier…

Get Last Insert ID in PHP with MySQL PDO and MySQLi

Keeping track of the last record inserted is often important. Whether you are managing user registrations, processing orders, or handling…

PHP compact Function: Assoc Array from Variables

The PHP compact function is a way to pull variables into an array. In this article, you will learn how…

Inheritance in PHP: Share Code from Class to Class & Examples

PHP developers copied and pasted code across multiple files before inheritance came, which made updates difficult. They updated functions in…

PHP array_intersect_assoc: How it Works with Examples

PHP array_intersect_assoc compares values and keys in arrays. It returns matches with the same key and value from all arrays…

PHP array_map Function: How to Transform Arrays with Examples

PHP added the array_map() function to help you apply one function to each item in an array. Understand the array_map…

PHP substr Function: How to Extract and Manipulate Strings

The substr() function in PHP returns part of a string. You give it a string, a starting point, and optionally…

Previous Article

PHP implode Function: Join Array Values into a String

Next Article

PHP foreach Loop: How to Access Keys & Values in Arrays

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.