PHP function str_repeat() – Repeat a string

The str_repeat() function is used to repeat a string, a specified number of times. This function was introduced in PHP4. The function returns a string consisting of count copies of string appended to each other. If the count is not greater than 0, an empty string is returned.

Syntax:

str_repeat(string $string, int $times): string

Parameters

Parameter Description
string The string to be repeated.
times Number of time the string string should be repeated.
Note: times has to be greater than or equal to 0. If the times is set to 0, the function will return an empty string.

Return Values

Returns the repeated string.

Examples

Example 1:

<?php
echo str_repeat(“*-”, 8);
?>

The output of the above program is as follows:

*-*-*-*-*-*-*-*-

Example 2: Print a small Dots-and-Boxes game grid.

<?php 
echo str_repeat (str_repeat (' .', 10) . "\n", 10); 
?>

Output:

. . . . . . . . . . 
. . . . . . . . . . 
. . . . . . . . . . 
. . . . . . . . . . 
. . . . . . . . . . 
. . . . . . . . . . 
. . . . . . . . . . 
. . . . . . . . . . 
. . . . . . . . . . 
. . . . . . . . . .
Related Post