In PHP development, array operations are the most common link in daily work. We are doing "cleaning arrays" almost every day. Whether it is processing form data submitted by users or cleaning up data returned by interfaces, one of the most common needs is to remove null values from an array .
Fortunately, PHP provides a very elegant method: array_filter() . This article will take you into the deep understanding of the usage of this function and share some practical tips to help you filter empty elements in an array efficiently and flexibly.
The default behavior of PHP array_filter() is to remove elements with the value "false" in the array, including:
Empty string ''
Number 0 and string '0'
null
false
Empty array []
Let’s take a look at the simplest example:
$data = ['apple', '', null, 'banana', 0, '0', false];
$filtered = array_filter($data);
print_r($filtered);
The output result is:
Array
(
[0] => apple
[3] => banana
)
You will find that array_filter() removes all the values that "looks like no content" by default. This usage is good enough for most scenarios.
If you don't want '0' or 0 to be filtered out, you can customize a callback function, let array_filter() filter out only values you really think are "empty", such as null or '' .
$data = ['title' => '', 'price' => 0, 'available' => false, 'sku' => '0', 'description' => null];
$filtered = array_filter($data, function($value) {
return !is_null($value) && $value !== '';
});
print_r($filtered);
Output:
Array
(
[price] => 0
[available] =>
[sku] => 0
)
This method is particularly suitable for processing user form data or configuration items, and will not accidentally delete meaningful "zero values".
Suppose you want to send the data entered by the user to an API through a POST request, we do not want to pass the null value over:
$formData = [
'name' => 'Zhang San',
'email' => '',
'phone' => null,
'age' => 25
];
$cleanData = array_filter($formData, function($val) {
return !is_null($val) && $val !== '';
});
$apiUrl = 'https://api.m66.net/user/submit';
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($cleanData),
]
];
$context = stream_context_create($options);
$result = file_get_contents($apiUrl, false, $context);
echo $result;
In this way, we only send valid data to avoid letting the API receive a bunch of useless fields.
If your array is multidimensional, such as a nested form submitted from the front end, you need to clean it up recursively:
function recursive_filter(array $input) {
foreach ($input as $key => &$value) {
if (is_array($value)) {
$value = recursive_filter($value);
}
}
return array_filter($input, function($val) {
return $val !== '' && !is_null($val);
});
}
$data = [
'user' => [
'name' => 'Li Si',
'email' => '',
'tags' => ['', null, 'developer']
],
'status' => null
];
$cleaned = recursive_filter($data);
print_r($cleaned);
After processing this way, your array will be clean and will not miss empty values or delete valid content incorrectly.
Through the above case, we can see:
The default behavior of array_filter() is already very powerful, quickly removing various "false values".
With custom callbacks, you can precisely control what to filter.
When dealing with complex structures, it can be easily dealt with in recursive ways.
In actual development, it can be used to clean form data, interface request parameters, and even data filtering before database writing.
In short, the more skillful you use this function, the cleaner your data will be and the more elegant your code will be!