PHP str_repeat is an inbuilt function in PHP. It repeats a string for a specified number of times. Both the string and the number are the arguments to the function. In this article, we will discuss the PHP str_repeat Function. Also, we will discuss a few examples of using it.
string str_repeat ( $string, $number )
The PHP str_repeat Function expects two mandatory parameters. The description of the parameters is as follows:
- $string: The first parameter to the function is the string you want to repeat.
- $number: The second parameter to the function is the number of times you want to repeat the string. The number should be greater than 0. However, if you pass 0 as the number, the function returns an empty string.
The function returns a string after repeating the specified string the given number of times. However, if you pass 0 as the number, the function returns an empty string.
Input: str_repeat('Concatly ', 3); Output: Concatly Concatly Concatly
Let’s discuss a few examples of using the function.
Example 1: Simple Usage
<?php echo str_repeat('Concatly ', 3); ?>
In the above example, the string ‘Concatly’ will print three times.
OUTPUT: Concatly Concatly Concatly
Example 2: Passing 0 as the Number
However, if you pass 0 as the number, the function returns an empty string as follows:
<?php var_dump(str_repeat('Concatly ', 0)); ?>
OUTPUT: string(0) ""
Vishesh is currently working as an Intermediate Software Engineer with Orion Health, New Zealand. He graduated with a Masters in Information Technology from the University of Auckland in 2021. With more than 4 years of work experience, his expertise includes Java, Python, Machine Learning, PHP, Databases, Design and Architecture.