How To Remove Empty Elements From An Array In PHP?

Published October 10, 2024

Problem: Removing Empty Elements from PHP Arrays

Removing empty elements from arrays in PHP is a common task when working with data. Empty elements can take up space and cause issues in data processing or display. This process involves finding and removing array elements that have no value or are considered empty by PHP standards.

The Challenge of Removing Empty Elements

Limitations of Basic Approaches

Removing empty elements from arrays in PHP can be difficult, especially when using simple methods. Two common approaches that often don't work well are foreach loops and the empty() function.

Using foreach loops to remove empty elements can cause problems. In the example, the loop goes through the array, but unset($link) only removes the local variable in the loop, not the actual array element. This means the original array stays the same.

The empty() function also has limits when used for this task. It can find empty elements, but it doesn't remove them from the array on its own. Also, empty() sees several values as empty, including the number 0 and the string "0", which you might not always want to remove.

These simple approaches often need extra steps or changes to work correctly, making them less useful for removing empty elements from arrays. More advanced methods, like array_filter(), offer better and easier solutions for this task.

Example: Incorrect Use of foreach Loop

$array = [1, '', 2, null, 3, false, 4, '0', 5];
foreach ($array as $key => $value) {
    if (empty($value)) {
        unset($value);
    }
}
// The $array remains unchanged

Solutions for Removing Empty Elements

Using array_filter() Function

The array_filter() function in PHP removes empty elements from arrays. You can use it like this:

$cleanArray = array_filter($originalArray);

This line removes elements PHP considers empty, including empty strings, null values, and false.

Benefits of using array_filter():

  • Simple: It needs little code, making scripts easier to read.
  • Fast: It works quicker than manual loops, especially for big arrays.
  • Built-in: It's part of PHP, so you don't need extra libraries.

Tip: Preserve array keys

If you want to keep the original array keys after filtering, you can pass the ARRAY_FILTER_USE_BOTH flag as the third argument to array_filter():

$cleanArray = array_filter($originalArray, null, ARRAY_FILTER_USE_BOTH);

This preserves the original keys of the non-empty elements in the resulting array.

Custom Callback Functions with array_filter()

For specific filtering needs, you can use custom callback functions with array_filter(). This lets you define what "empty" means in your context.

Examples of custom callbacks for different PHP versions:

For PHP 7.4 and later, use arrow functions:

$cleanArray = array_filter($originalArray, fn($value) => !is_null($value) && $value !== '');

For PHP 5.3 to 7.3, use anonymous functions:

$cleanArray = array_filter($originalArray, function($value) { 
    return !is_null($value) && $value !== ''; 
});

For PHP versions before 5.3, use create_function():

$cleanArray = array_filter($originalArray, create_function('$value', 'return $value !== "";'));

These custom callbacks let you keep certain values that might be empty by default, like the string '0'.

To keep array keys in order after filtering, use the array_values() function:

$cleanArray = array_values(array_filter($originalArray));

This method gives you control over what elements to keep or remove from your array, making it useful for handling empty elements in various cases.