PHP
Check if an Array is Empty or Contains Only Empty Values
Learn a robust method to determine if a PHP array is completely empty or if all its elements are considered empty (null, '', false, 0), useful for validation.
<?php
function isArrayEmptyOrOnlyEmptyValues(array $arr): bool {
if (empty($arr)) {
return true;
}
// Filter out all values that are considered 'empty'
$nonEmptyValues = array_filter($arr, function($value) {
return !empty($value);
});
return empty($nonEmptyValues);
}
$array1 = [];
$array2 = [null, '', false, 0];
$array3 = ['hello', 'world'];
$array4 = [null, 'text', false];
echo 'Array 1 empty or only empty values? ' . (isArrayEmptyOrOnlyEmptyValues($array1) ? 'Yes' : 'No') . "
";
echo 'Array 2 empty or only empty values? ' . (isArrayEmptyOrOnlyEmptyValues($array2) ? 'Yes' : 'No') . "
";
echo 'Array 3 empty or only empty values? ' . (isArrayEmptyOrOnlyEmptyValues($array3) ? 'Yes' : 'No') . "
";
echo 'Array 4 empty or only empty values? ' . (isArrayEmptyOrOnlyEmptyValues($array4) ? 'Yes' : 'No') . "
";
// Output:
// Array 1 empty or only empty values? Yes
// Array 2 empty or only empty values? Yes
// Array 3 empty or only empty values? No
// Array 4 empty or only empty values? No
?>
How it works: This function provides a reliable way to check if an array is truly empty or if it only contains values that PHP considers 'empty' (like `null`, empty strings `''`, `false`, or `0`). It first checks for a completely empty array. If not empty, `array_filter()` with a custom callback `!empty($value)` is used to remove all 'empty' elements. If the resulting filtered array is also empty, it means the original array contained only empty values.