Quick solution

The quickest way to remove empty array elements in a PHP array is using the array_filter() function:

PHP

This function will simply loop through the array and return the elements that are not empty, achieving the result we wanted. To better understand this function, below are more detail instructions.

To remove empty array elements

Using array_filter() to remove empty array elements

The basic method to remove empty array elements in a PHP array is using array_filter() function. Assuming we have this array with various empty elements:

PHP

We wanted to only keep the array elements containing values and remove empty ones. This can be done easily using array_filter():

PHP

How does array_filter() work?

Based on PHP.net official documentation on array_filter() function, the function works by accepting minimum of one argument – the array to filter:

PHP

  • $array is the array we want to filter
  • $callback is the callback function to loop through the array. If no $callback is supplied, all empty entries of array will be removed. That’s how empty array elements are removed.

However, sometimes this function doesn’t work as expected – the assuming empty elements aren’t removed. Why is it? Because it depends on how PHP treats what is empty with the empty() function. There are blank Unicode values that are a spacing, null values that are not treated as empty, therefore not being removed.

How can we sort this issue? That’s when extra callback is useful.

Optional callback for extra removal functionality

Using callback to remove empty array elements will help cases with elements having special characters not being treated as ’empty’, or simply as the character ‘0’ (that we wanted to remove) to be fully removed from the array.

We will create the callback function first. Based on PHP.net documentation, If the callback function returns true, the current value from array is returned into the result array. So we need to return true on the elements we want to keep, which is the valid elements:

PHP

Then, we can pass the callback function into the actual array_filter() function:

PHP

Tips: Additional array elements cleaning

There might be blank spaces in your array elements that aren’t counted as ’empty’ defined by PHP, which you can try to trim the spaces using trim() function with array_map() first before cleaning the array:

PHP

Final thoughts

These are the guide to remove empty array elements using PHP, with some extra tips on cleaning the array elements before filtering it. We hope that this short guide would help you using array_filter() and array_map() effectively.