logo CodeStepByStep logo


Language/Type: PHP arrays traversals

Write a function named n_copies that accepts an array of elements $arr as a parameter and returns a new array $arr2, with each element value $n from $arr replaced by $n consecutive copies of the value $n at the same relative location in the array.

For example, if an array named $arr stores the following element values:

[3, 5, 0, 2, 2, -7, 0, 4]

Then the call of $arr2 = $n_copies($arr); should result in a new array $arr2 containing the following elements:

[3, 3, 3, 5, 5, 5, 5, 5, 2, 2, 2, 2, 4, 4, 4, 4]

The idea is that the value 3 was replaced by three 3s; the 5 was replaced by five 5s; and so on. Any element whose value is 0 or negative should not be kept in the returned array (as with 0 and -7 above).


  • In solving this problem, you must create a single new array to be returned, but aside from that, do not create any other data structures such as temporary arrays or strings.
  • You may use as many simple variables (such as integers) as you like.
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.