How to Remove Empty Elements from an Array in PHP

Updated: January 10, 2024 By: Guest Contributor Post a comment

Introduction

Arrays are a fundamental aspect of PHP, a server-side scripting language used to develop web applications. Proper management of arrays, which includes filtering out empty elements, is crucial for performance and accuracy in PHP applications.

In PHP, an array can contain empty elements, usually empty strings (”), NULL, or even unset elements. These elements can occur as a result of data processing, user inputs, or after certain array operations. It’s essential to know how to remove such elements to ensure the data integrity of your arrays.

Basic Techniques

Using array_filter()

One of the simplest ways to filter empty elements from an array is by using the built-in array_filter() function. By default, array_filter() removes all values from an array that are equivalent to false, which includes empty strings, NULL, 0, and false itself.

<?php
$array = array("apple", "", "banana", NULL, "0", "orange", false);
$filtered_array = array_filter($array);
print_r($filtered_array);
// Output:
// Array
// (
//     [0] => apple
//     [2] => banana
//     [5] => orange
// )
?>

Notice how numeric string zero (‘0’) and FALSE are removed in addition to the empty string and NULL.

Preserving keys

By default, array_filter() does not preserve numeric keys. If your array contains numeric keys that you need to keep, you can pass a second argument, ARRAY_FILTER_USE_BOTH, which will preserve the original array’s keys.

<?php
$array = array(1 => "apple", 2 => "", 3 => "banana", 4 => NULL);
$filtered_array = array_filter($array, fn($value, $key) => !empty($value) || $key === 2, ARRAY_FILTER_USE_BOTH);
print_r($filtered_array);
// Output:
// Array
// (
//     [1] => apple
//     [3] => banana
// )
?>

This preserves the keys but notice that despite telling array_filter to remove only non-empty elements, key 2 with an empty string is still there. This is because the anonymous function specifically allows key 2 irrespective of its value.

Removing specific empty values

If you need to fine-tune which empty values to remove, such as only the NULL values, you can pass a custom callback function to array_filter().

<?php
$array = array("apple", "", "banana", NULL, "0", "orange");

$filtered_array = array_filter($array, function($value) {
    // Remove only NULL values
    return !is_null($value);
});

print_r($filtered_array);
// Output:
// Array
// (
//     [0] => apple
//     [1] => 
//     [2] => banana
//     [4] => 0
//     [5] => orange
// )
?>

In the example above, only NULL is treated as empty and removed from the final array.

Advanced Usage

For more complex situations, such as arrays with nested arrays or object properties, custom functions may be necessary. Here we’ll go through cleaning multi-dimensional arrays and filtering based on user-defined criteria.

Cleaning Multi-Dimensional Arrays

To handle multi-dimensional arrays, you need a recursive function. You can adapt the array_filter() function to work recursively or create a custom function altogether.

<?php
function array_filter_recursive($input) {
    foreach ($input as &$value) {
        if (is_array($value)) {
            $value = array_filter_recursive($value);
        }
    }

    return array_filter($input);
}

$array = array("apple", array("", "banana", NULL), "orange");

$clean_array = array_filter_recursive($array);
print_r($clean_array);
// Output:
// Array
// (
//     [0] => apple
//     [1] => Array
//         (
//             [1] => banana
//         )
//     [2] => orange
// )
?>

This recursive approach ensures that all levels of the array are filtered.

Textual Callback Filter

Another more advanced technique is to create a callback filter that removes elements based on some textual criteria. For example, you might want to remove all strings that contain only whitespace.

<?php
function remove_whitespace_elements($value) {
    return !preg_match('/^\s*$/', $value);
}

$array = array("apple", " ", " banana ", "", "  ", "orange");

$filtered_array = array_filter($array, 'remove_whitespace_elements');

print_r($filtered_array);
// Output:
// Array
// (
//     [0] => apple
//     [2] =>  banana 
//     [5] => orange
// )
?>

The regular expression in the remove_whitespace_elements() function checks if the value consists of only whitespace characters and removes such elements from the array.

Conclusion

Removing empty elements from an array in PHP can enhance the quality and reliability of your data handling. As this guide has shown, there are various methods and functions suited to different circumstances and requirements. The use of array_filter() is versatile and can often provide a quick and effective solution. For more complex requirements, writing custom functions enables greater control over what constitutes an ’empty’ element. Regardless of the method you choose, cleaning your arrays is a key step towards more robust and efficient PHP code.