78. PHP Program to Separate Zeros from the given Array elements.
How does this program work?
- This program is used to find the zeros from the given array elements using PHP.
Here is the code
<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>