Skip to content

Remove Empty Array Elements and reindex in PHP

Last updated on January 30, 2021

The built-in array_filter() the 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 that we can specify
ARRAY_FILTER_USE_KEY – passkey 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
    [1] => PHP Tutorials
    [5] => Python
)

*/

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

 PHP
    [1] => Java
    [2] => 2
    [3] => -5
    [4] => Python
    [5] => 10
    [6] => 1
)

*/

5 1 vote
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments