w3resource

PHP Exercises: Create a new array from a given array of integers shifting all zeros to left direction

PHP Basic Algorithm: Exercise-127 with Solution

Write a PHP program to create a new array from a given array of integers shifting all zeros to left direction.

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 to keep track of the position of '0'
    $pos = 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 equal to '0'
        if ($numbers[$i] == 0)
        {
            // Swap the positions of the current element and the element at position $pos
            $numbers[$i] = $numbers[$pos];
            $numbers[$pos++] = 0;
        }
    }

    // Return the modified array
    return $numbers;
}   

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

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

Sample Output:

New array: 0,0,1,3,5,7,2,9,11

Flowchart:

Flowchart: Create a new array from a given array of integers shifting all zeros to left direction.

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP program to create a new array taking the elements after the element value 5 from a given array of integers.
Next: Write a PHP program to create a new array after replacing all the values 5 with 0 shifting all zeros to right direction.

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://www.w3resource.com/php-exercises/basic-algorithm/php-basic-algorithm-exercise-127.php