PHP Challenges: Push all zeros to the end of an array
Write a PHP program to push all zeros to the end of an array.
Input : (0,2,3,4,6,7,10)
Explanation :
Sample Solution :
PHP Code :
<?php
// Function to move all zeroes to the end of an array while maintaining the order of non-zero elements
function move_zero($arr)
{
// Initialize a counter to track the position where non-zero elements will be placed
$count = 0;
// Get the size of the array
$n = sizeof($arr);
// Iterate through the array
for ($i = 0; $i < $n; $i++)
{
// If the current element is non-zero
if ($arr[$i] != 0)
{
// Move the non-zero element to the position tracked by $count and increment $count
$arr[$count++] = $arr[$i];
}
}
// Fill the remaining positions in the array with zeroes
while ($count < $n)
{
$arr[$count++] = 0;
}
// Return the modified array
return $arr;
}
// Test arrays
$num_list1 = array(0, 2, 3, 4, 6, 7, 10);
$num_list2 = array(10, 0, 11, 12, 0, 14, 17);
// Test the move_zero function with the test arrays and print the results
print_r(move_zero($num_list1));
print_r(move_zero($num_list2));
?>
Explanation:
Here is a brief explanation of the above PHP code:
- Function definition (move_zero):
- The function "move_zero()" takes an array '$arr' as input.
- It initializes a counter '$count' to keep track of the position where non-zero elements will be placed.
- Inside the function:
- It iterates through the array '$arr'.
- For each element in the array, if it is non-zero, it moves that element to the position tracked by '$count' and increments '$count'.
- After iterating through the array, it fills the remaining positions in the array with zeroes.
- Function Call & Testing:
- The "move_zero()" function is tested with two different arrays ($num_list1 and $num_list2).
- Finally, the "print_r()" function prints the modified arrays after moving zeroes to the end.
Sample Output:
Array ( [0] => 2 [1] => 3 [2] => 4 [3] => 6 [4] => 7 [5] => 10 [6] => 0 ) Array ( [0] => 10 [1] => 11 [2] => 12 [3] => 14 [4] => 17 [5] => 0 [6] => 0 )
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a PHP program to check if a given string is an anagram of another given string.
Next: Write a PHP program to find majority element in an array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics