w3resource

PHP Exercises: Create new array from a given array of integers shifting all even numbers before all odd numbers

PHP Basic Algorithm: Exercise-129 with Solution

Write a PHP program to create new array from a given array of integers shifting all even numbers before all odd numbers.

Sample Solution:

PHP Code :

<?php
// Define a function named 'test' that takes an array of numbers as a parameter
function test($numbers)
{ 
    // Initialize a variable '$index' to keep track of the position of even numbers
    $index = 0;

    // Iterate through the elements of the input array using a for loop
    for ($i = 0; $i < sizeof($numbers); $i++)
    {
        // Check if the current element is an even number
        if ($numbers[$i] % 2 == 0)
        {
            // Swap the current even number with the one at the position indicated by '$index'
            $temp = $numbers[$index];
            $numbers[$index] = $numbers[$i];
            $numbers[$i] = $temp;

            // Increment '$index' to the next position for the next even number
            $index++;
        }
    }

    // Return the modified array with even numbers moved to the front
    return $numbers;
}   

// Call the 'test' function with an example array and store the result in the variable 'result'
$result = test([1, 2, 5, 3, 5, 4, 6, 9, 11]);

// Print the result array as a string
echo "New array: " . implode(',', $result);
?>

Sample Output:

New array: 2,4,6,3,5,1,5,9,11

Flowchart:

Flowchart: Create new array from a given array of integers shifting all even numbers before all odd numbers.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new array after replacing all the values 5 with 0 shifting all zeros to right direction.
Next: Write a PHP program to check if the value of each element is equal or greater than the value of previous element of a given array of integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-129.php