logo CodeStepByStep logo


Language/Type: PHP exam arrays traversals

Write a function named even_before_odd that accepts an array of integers as a parameter and rearranges its elements so that all even values appear before all odds, in the same relative order. For example, if the following array is passed to your function:

$numbers = [5, 2, 4, 9, 3, 6, 2, 1, 11, 1, 10, 4, 7, 3];

Then after the function has been called, the array's elements must be changed to the following order. Notice that all even values appear before all odd values, in the same relative order that they appeared in the original array.

           [2, 4, 6, 2, 10, 4, 5, 9, 3, 1, 11, 1, 7, 3]

Do not make any assumptions about the length of the array or the range of values it might contain. For example, the array might contain no even elements or no odd elements.

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.