← Back to all snippets
PHP

Check if Array Contains Only Empty or Null Values

Verify if a PHP array is effectively empty by checking if all its elements are either null, empty strings, or other "empty" values.

<?php
function is_array_effectively_empty(array $array): bool
{
    // array_filter with no callback removes all empty values (false, null, '', 0, [])
    return empty(array_filter($array));
}

// Test cases for effectively empty
$array1 = ['hello', 'world'];
$array2 = ['', null, false, 0, []];
$array3 = ['value', '', null];
$array4 = [];
$array5 = [0, ''];
$array6 = [' ', "\t", "
"]; // Non-empty string whitespace

// echo "Array 1 ('hello', 'world'): " . (is_array_effectively_empty($array1) ? 'Empty' : 'Not Empty') . "
"; // Not Empty
// echo "Array 2 ('', null, false, 0, []): " . (is_array_effectively_empty($array2) ? 'Empty' : 'Not Empty') . "
"; // Empty
// echo "Array 3 ('value', '', null): " . (is_array_effectively_empty($array3) ? 'Empty' : 'Not Empty') . "
"; // Not Empty
// echo "Array 4 ([]): " . (is_array_effectively_empty($array4) ? 'Empty' : 'Not Empty') . "
"; // Empty
// echo "Array 5 (0, ''): " . (is_array_effectively_empty($array5) ? 'Empty' : 'Not Empty') . "
"; // Empty
// echo "Array 6 (' ', '\t', '
'): " . (is_array_effectively_empty($array6) ? 'Empty' : 'Not Empty') . "
"; // Not Empty (whitespace is not empty)

// For strict "only nulls/empty strings" (excluding 0, false, etc.):
function contains_only_null_or_empty_strings(array $array): bool
{
    foreach ($array as $value) {
        if ($value !== null && $value !== '') {
            return false;
        }
    }
    return true;
}

// echo "Strict Array 2 ('', null, false, 0, []): " . (contains_only_null_or_empty_strings($array2) ? 'Empty' : 'Not Empty') . "
"; // Not Empty (due to false, 0, [])
// echo "Strict Array with only nulls/empty strings: " . (contains_only_null_or_empty_strings(['', null, '']) ? 'Empty' : 'Not Empty') . "
"; // Empty
How it works: This snippet provides two functions for checking the "emptiness" of an array. The `is_array_effectively_empty` function uses `array_filter()` without a callback, which automatically removes all values considered "empty" by PHP (e.g., `false`, `null`, `''`, `0`, `[]`). If the resulting array is empty, it means the original array contained only such values. The `contains_only_null_or_empty_strings` function offers a stricter check, iterating through the array to ensure every element is *strictly* `null` or an empty string `''`, ignoring other falsy values.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs