Remove Empty Array Elements and Reindex In PHP
In this article you will learn how to remove empty array elements and reindex from an array in PHP. You can easily do it after use array_values() and array_filter() function together to remove empty array elements and reindex from an array in PHP.
array_filter() function
The PHP array_filter() function remove empty array elements or values from an array in PHP. This will also remove blank, null, false, 0 (zero) values.
array_values() function
The PHP array_values() function returns an array containing all the values of an array. The returned array will have numeric keys, starting at 0 and increase by 1.
Remove Empty Array Elements and Reindex In PHP
First let’s see the $stack array output :
<?php $stack = array("PHP", "HTML", "CSS", "", "JavaScript", null, 0); print_r($stack); ?>
Output:
Array ( [0] => PHP [1] => HTML [2] => CSS [3] => [4] => JavaScript [5] => [6] => 0 )
In above output we want to remove blank, null, 0 (zero) values and then reindex array elements. Now we will use array_values() and array_filter() function together like in below example:
<?php $stack = array("PHP", "HTML", "CSS", "", "JavaScript", null, 0); print_r(array_values(array_filter($stack))); ?>
Output:
Array ( [0] => PHP [1] => HTML [2] => CSS [3] => JavaScript )