Remove Zero From Array In PHP



If we are working with the PHP array then there is some condition occurs when we want to remove the empty elements from an array. It is very easy and you can remove the empty elements of the array by using array_filter() without a callback function.

$resultarray = array_filter( $resultarray );

Example:

$resultarray = array( 0, 'green', '', 'red');
print_r(array_filter($resultarray));

Array
(
[1] => 'green'
[3] => 'red'
)

you can also use the array_diff() it allows you to decide which elements to keep

$resultarray = array( 0, 'green', '', 'red');
print_r(array_diff($resultarray, array('')));

Array
(
[0] => 0
[1] => 'green'
[3] => 'red'
)

Note : Remember that Both functions leave “gaps” where the empty entries used, as in the above array you can see there is no 0 and 2 index it shows only the indexes which have values in it and in array_diff I have decided to delete only the blank array.

For removing the gaps from the resultant array you can use array_slice() as given below:

$resultarray = array( 0, 'green', '', 'red');
$resultarray = array_filter($resultarray);
print_r(array_slice($resultarray, 0));

Array
(
[0] => 'green'
[1] => 'red'
)

Hope this will help to someone.