logo CodeStepByStep logo

repeat

Language/Type: PHP arrays

Write a function named repeat that accepts an array of elements and an integer $k as parameters and that replaces each element with $k copies of that element.

For example, if an array stores the values ["how", "are", "you?"] before the function is called and $k is 4, it should store the values ["how", "how", "how", "how", "are", "are", "are", "are", "you?", "you?", "you?", "you?"] after the function finishes executing. If the array instead stored [143, 154] with the same $k, it should then store the values [143, 143, 143, 143, 154, 154, 154, 154] after the function finishes executing (in other words, the same behavior is expected regardless of what type of elements the array contains).

If $k is 0 or negative, the array should be empty after the call. You may assume that the array passed is non-null.

A note about references in PHP: In order to write a function passes a parameter as reference (thus modifying its state), you'll need to prepend "&" to the variable declaration in the function header. For example, a function foo that modifies the state of an array parameter may be defined as:

function foo(&$arr) { ... }
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.