Posted by Arjun on Monday 27th July 2020

Remove Empty Array Elements and reindex in PHP

The built-in array_filter() function removes all the empty elements, zeros, false and null values from an array. This function uses a callback function to filter the array values. If no callback function is specified, it removes the empty elements, zeros, false and null values.

Syntax:
array_filter ( array $array [, callable $callback [, int $flag = 0 ]] ) : array

Here:
$array is an array to iterate over,
$callback is a callback function if no callback is supplied, all entries of the array equal to FALSE will be removed.
$flag determining what arguments are sent to the callback, default is zero, it means only array values will be passed to the callback function. Following are the two flangs which we can specify
ARRAY_FILTER_USE_KEY - pass key as the only argument to callback instead of the value
ARRAY_FILTER_USE_BOTH - pass both value and key as arguments to callback instead of the value

array_filter() function Example
 $array = array("PHP", "Java", 2, null, -5, "Python", 10, false, "", true);
 $filtered_array = array_filter($array);
 print_r($filtered_array );
/* expected output: 
Array(
    [0] => PHP
    [1] => PHP Tutorials
    [2] => 2
    [4] => -5
    [5] => Python
    [6] => 10
    [9] => 1
)
*/
array_filter() function Example with callback
<?php
$array = array("PHP", "PHP Tutorials", 2, null, -5, "Python", 10, false, "", true);
$filtered_array = array_filter($array,function($value){
    return $value && is_string($value);
});
print_r($filtered_array);
/* expected output:
Array
(
    [0] => PHP
    [1] => PHP Tutorials
    [5] => Python
)

*/

You can remove the empty value and then reindex array elements too easily, below is the example

<?php
$array = array("PHP", "Java", 2, null, -5, "Python", 10, false, "", true);
$filtered_array = array_filter($array); // filter empty, null, false
$filtered_array_reIndex = array_values($filtered_array); // reindex
print_r($filtered_array_reIndex );
/* expected output: 
Array
(
    [0] => PHP
    [1] => Java
    [2] => 2
    [3] => -5
    [4] => Python
    [5] => 10
    [6] => 1
)

*/