Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

str_repeat
string
php
communitycreator

What is the str_repeat method in PHP?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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
?>

RELATED TAGS

str_repeat
string
php
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring