w3resource logo


php exercises

PHP Challenges: Push all zeros to the end of an array

PHP Challenges - 1: Exercise-22 with Solution

Write a PHP program to push all zeros to the end of an array.

Input : (0,2,3,4,6,7,10)
Output :

(
[0] => 2
[1] => 3
[2] => 4
[3] => 6
[4] => 7
[5] => 10
[6] => 0
)

Explanation :

PHP: Push all zeros to the end of an array

Sample Solution :-

PHP Code :

<?php
function move_zero($arr)
{
   $count = 0;
   $n = sizeof($arr);
    
    for ($i = 0; $i < $n; $i++)
    {
        if ($arr[$i] != 0)
          {
            $arr[$count++] = $arr[$i]; 
          }
     }
 
    // Let all non-zero elements have been shifted towards front  
    
    while ($count < $n)
    {
        $arr[$count++] = 0;
    }

    return $arr;
}
$num_list1 = array(0,2,3,4,6,7,10);
$num_list2 = array(10,0,11,12,0,14,17);
print_r(move_zero($num_list1));
print_r(move_zero($num_list2));
?>

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 Flowchart: Push all zeros to the end of an array

PHP Code Editor:

<?php
function move_zero($arr)
{
   $count = 0;
   $n = sizeof($arr);
    
    for ($i = 0; $i < $n; $i++)
    {
        if ($arr[$i] != 0)
          {
            $arr[$count++] = $arr[$i]; 
          }
     }
 
    // Let all non-zero elements have been shifted towards front  
    
    while ($count < $n)
    {
        $arr[$count++] = 0;
    }

    return $arr;
}
$num_list1 = array(0,2,3,4,6,7,10);
$num_list2 = array(10,0,11,12,0,14,17);
print_r(move_zero($num_list1));
print_r(move_zero($num_list2));
?>

Improve this sample solution and post your code through Disqus



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program