Write a PHP program to create new array from a given array of integers shifting all even numbers before all odd numbers
<?php function test($numbers) { $index = 0; for ($i = 0; $i < sizeof($numbers); $i++) { if ($numbers[$i] % 2 == 0) { $temp = $numbers[$index]; $numbers[$index] = $numbers[$i]; $numbers[$i] = $temp; $index++; } } return $numbers; } $result = test([1, 2, 5, 3, 5, 4, 6, 9, 11] ); echo "New array: " . implode(',', $result);
Sample Output:
New array: 2,4,6,3,5,1,5,9,11
total answers (1)
start bookmarking useful questions and collections and save it into your own study-lists, login now to start creating your own collections.
<?php function test($numbers) { $index = 0; for ($i = 0; $i < sizeof($numbers); $i++) { if ($numbers[$i] % 2 == 0) { $temp = $numbers[$index]; $numbers[$index] = $numbers[$i]; $numbers[$i] = $temp; $index++; } } return $numbers; } $result = test([1, 2, 5, 3, 5, 4, 6, 9, 11] ); echo "New array: " . implode(',', $result);Sample Output:
need an explanation for this answer? contact us directly to get an explanation for this answer