How to Remove Empty Array Elements in PHP

Frequently, some elements in an array can be empty, and it is necessary to remove them. In this short tutorial, we will provide you with the right function to do that.

The most common and correct way is to use the array_filter function. It will remove any element that is evaluated as FALSE (null, false, '', 0). By adding a callback function, you can customize the filter.

Watch a course Learn object oriented PHP

Here is how the array_filter works:

<?php

$array = [0, 'amir', 'test', 490, null, '', 'Hello world'];
$array = array_filter($array);

var_dump($array);

?>

Result

array(4) {
  [1] =>
  string(4) "amir"
  [2] =>
  string(4) "test"
  [3] =>
  int(490)
  [6] =>
  string(11) "Hello world"
}

In the example above, the value of $array is what is demonstrated below it in the brackets.

That operates properly but may leave index gaps inside an array. Luckily, you can fix it with the help of array_values for re-indexing the array like this:

<?php

$array = [0, 'amir', 'test', 490, null, '', 'Hello world'];
$array = array_values(array_filter($array));

var_dump($array);

?>

Result

array(4) {
  [0] =>
  string(4) "amir"
  [1] =>
  string(4) "test"
  [2] =>
  int(490)
  [3] =>
  string(11) "Hello world"
}

In this example, as well, the value of $array is what is demonstrated below it in the brackets.

Describing the array_filter Function

This function is capable of iterating over every value in the array and pass them to the callback function.

Once the callback function returns True, the current value from the array gets back into the result array.

The array_filter function has the following parameters: array, callback, and flag.

The first one is the array to iterate over. Callback is the callback function to apply. And, the flag specifies what arguments are forwarded to the callback.