w3resource

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


127. Shift Zeros to Left in Array

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.

For more Practice: Solve these Related Problems:

  • Write a PHP script to rearrange an array so that all zeros are moved to the left while preserving the order of non-zero elements.
  • Write a PHP function to partition an array into zeros and non-zeros, then merge them with zeros preceding.
  • Write a PHP program to use a custom sorting algorithm to reposition zeros to the left side of the array.
  • Write a PHP script to iterate over an array and rebuild it with zeros leading and the remainder following in original order.

Go to:


PREV : Array Elements After Value 5.
NEXT : Replace 5 with 0 and Shift Zeros to Right.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.