PHP Exercises: Create a new string which is n copies of a given string
25. n Copies of a Given String
Write a PHP program to create a new string which is n (non-negative integer) copies of a given string.
Sample Solution:
PHP Code :
Explanation:
- Function Definition:
- The test function takes two parameters: $s (a string to repeat) and $n (the number of times to repeat it).
- Initialize Result Variable:
- An empty string "$result" is initialized to accumulate the repeated string.
- Loop to Repeat the String:
- A for loop runs $n times, concatenating $s to $result in each iteration. By the end of the loop, $result contains $s repeated $n times.
- Return Result:
- The function returns the final accumulated string stored in $result.
Output:
JSJS JSJSJS JS
Visual Presentation:

Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to generate a new string consisting of n concatenated copies of an input string using loops.
- Write a PHP function to replicate a string n times by employing built-in functions like str_repeat and custom error checks.
- Write a PHP program to simulate string repetition using iterative concatenation instead of built-in functions.
- Write a PHP script to validate the integer n and then output the repeated string, handling edge cases such as n equals 0.
Go to:
PREV : Uppercase Last 3 Characters of String.
NEXT : n Copies of First 3 Characters.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.