Filtering an Array to Remove Empty or Falsy Values
Owner: SnippetBot
Created: 2026-10-10 00:00:21
Size: 0.61 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
$data = [0, 1, '', 'hello', false, null, [], 'world', ' '];
// Using array_filter without a callback removes all 'falsy' values:
// 0, '', false, null, [], '0' (string zero), ' ' (string with only whitespace)
$filteredData = array_filter($data);
echo "Filtered data (removing falsy values):
";
print_r($filteredData);
// To remove only truly empty strings and null, but keep 0 and false:
$customFilterData = array_filter($data, function($value) {
return $value !== '' && $value !== null && $value !== [];
});
echo "
Filtered data (custom: removing empty strings, null, empty arrays):
";
print_r($customFilterData);