PHP
Removing Null, Empty, or Falsy Values from an Array
Efficiently clean up arrays by removing elements that are null, empty strings, or other falsy values using `array_filter` in PHP.
<?php
$data = [
'name' => 'John Doe',
'email' => '[email protected]',
'phone' => null,
'address' => '', // Empty string
'age' => 0, // Falsy integer
'is_active' => false, // Falsy boolean
'city' => 'New York',
'tags' => [], // Empty array
'description' => 'A non-empty string'
];
echo "Original array:
";
print_r($data);
// Method 1: Remove all falsy values (null, 0, false, '', [])
// array_filter with no callback removes all elements that evaluate to false.
$cleanedDataFalsy = array_filter($data);
echo "
Cleaned (falsy values removed):
";
print_r($cleanedDataFalsy);
/* Output:
Array
(
[name] => John Doe
[email] => [email protected]
[city] => New York
[description] => A non-empty string
)
*/
// Method 2: Remove only null values
$cleanedDataNull = array_filter($data, function($value) {
return $value !== null;
});
echo "
Cleaned (only null values removed):
";
print_r($cleanedDataNull);
/* Output:
Array
(
[name] => John Doe
[email] => [email protected]
[address] =>
[age] => 0
[is_active] =>
[city] => New York
[tags] => Array
(
)
[description] => A non-empty string
)
*/
// Method 3: Remove null and empty strings, but keep '0' and 'false'
$cleanedDataSpecific = array_filter($data, function($value) {
return $value !== null && $value !== '';
});
echo "
Cleaned (null and empty strings removed, 0/false kept):
";
print_r($cleanedDataSpecific);
/* Output:
Array
(
[name] => John Doe
[email] => [email protected]
[age] => 0
[is_active] =>
[city] => New York
[tags] => Array
(
)
[description] => A non-empty string
)
*/
?>
How it works: The `array_filter()` function is highly versatile for cleaning arrays. When called without a callback, it automatically removes all 'falsy' values (which include `null`, integer `0`, boolean `false`, empty strings `''`, and empty arrays `[]`). The snippet also demonstrates how to use a custom callback to achieve more granular control, such as specifically removing only `null` values, or removing both `null` and empty strings while preserving other falsy values like `0` or `false`, offering precise data sanitization capabilities.