Open In App

How to repeat a string to a specific number of times in PHP ?

A string is a sequence of characters stored in PHP. The string may contain special characters or numerical values or characters. The strings may contain any number of characters and may be formed by the combination of smaller substrings. 

Approach 1: Using for loop: An empty string variable is declared in order to store the contents of the final string. An integer value n is declared that indicates the number of times to repeat the string. Each time the original string is appended to the end of the final string variable declared. The contents of the final string are then displayed. 






<?php
  
// Declaring string variable 
$str = "Hi!GFG User.";
echo("Original string : ");
echo($str . "</br>");
  
// Declaring number of times 
$n = 3;
  
// Declaring empty string
$final_str = "";
  
// Looping over n times
for($i = 0; $i < $n; $i++) {
  
      // Appending str to final string value
    $final_str .= $str;
}
echo("Final string : ");
echo($final_str . "</br>");
  
?>

Output
Original string : Hi!GFG User.
Final string : Hi!GFG User.Hi!GFG User.Hi!GFG User.

Approach 2: Using str_repeat method: The in-built str_repeat() method in PHP can be used to repeat the specified string the specified number of times. The contents can be stored in a separate variable name. The method has the following syntax : 



str_repeat( str, n)

Parameters: 




<?php
    
// Declaring string variable 
$str = "Hi!GFG User.";
echo("Original string : ");
echo($str."</br>");
  
// Declaring number of times 
$n = 3;
  
// Computing final string
$final_str = str_repeat($str, $n);
echo("Final string : ");
echo($final_str . "</br>");
  
?>

Output
Original string : Hi!GFG User.
Final string : Hi!GFG User.Hi!GFG User.Hi!GFG User.

Article Tags :