You are here: Home / Topics / PHP Program to Separate Zeros from the given Array elements

PHP Program to Separate Zeros from the given Array elements

Filed under: PHP on 2022-11-15 10:51:43

Hello guys, this program is used to find all the zeros in any given array and shift those zeros in the last for example. 

Given array: 1 8 5 0 4 0 5 1 0 0 4 

Output: 1 8 5 4 5 1 4 0 0 0 0

Program::

//To separate zeros from the given array elements
<html>
     <head>
       <title>PHP Program To separate zeros from the given array elements</title>
    </head>
<body>
  <?php
function pushZerosToEnd(&$arr, $n)
{
// Count of non-zero elements
$count = 0;
//If element encountered is non-zero
//Then replace the element at index 'count' with this element
for ($i = 0; $i < $n; $i++)
if ($arr[$i] != 0)
$arr[$count++] = $arr[$i]; // Here count is incremented
// Now all non-zero elements have been shifted to front and 'count' is set as index of first 0.
//Make all elements 0 from count to end.
while ($count < $n)
$arr[$count++] = 0;
}
$arr = array(1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0, 9);
$n = sizeof($arr);
echo "Array Elements : \n";
foreach ($arr as $value)
{
echo $value." ";
}
pushZerosToEnd($arr, $n);
echo "The rearranged array is given below :\n";
for ($i = 0; $i < $n; $i++)
echo $arr[$i ] . " ";
return 0;
?>
  </body>
</html

About Author:
M
Mr. Dubey     View Profile
Founder and CEO of MCQ Buddy. I just like to help others.