logo CodeStepByStep logo


Language/Type: PHP recursion

Write a recursive function named repeat_string that accepts a String $str and an integer $n as parameters and that returns $str concatenated $n times. For example, the call of repeat_string("hello", 3) returns "hellohellohello". Your function should throw an Exception if passed any negative value for $n.


  • Do not declare any global variables.
  • Do not use any loops; you must use recursion.
  • Do not use any auxiliary data structures (e.g. arrays) or strings to solve this problem.
  • You are allowed to define other "helper" functions if you like; they are subject to these same constraints.
Function: Write a PHP function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.