<?php
// This section of code is unrelated to the article content, included only as a preliminary example
echo "PHP example program starting...\n";
$exampleArray = [1, 2, '', null, 5];
print_r($exampleArray);
?>
When working with arrays in PHP development, you often encounter arrays containing empty values such as empty strings, null, or false. To ensure accurate and efficient data handling, these empty values usually need to be filtered out. PHP provides the built-in array_filter function for this purpose.
The example array contains empty strings, null, and numbers:
$input = ["apple", "", null, "banana", false, 0, "cherry"];
Filter empty values using array_filter:
$result = <span class="function_ invoke__">array_filter</span>($input); <span class="function_ invoke__">print_r</span>($result);
Output:
Array
(
[0] => apple
[3] => banana
[6] => cherry
)
As you can see, the empty string "", null, and false have all been filtered out.
Sometimes you might only want to remove null or empty strings while keeping numbers like 0 or boolean false. You can define a custom callback function:
$result = <span class="function_ invoke__">array_filter</span>($input, function($value) {
return $value !== null && $value !== '';
});
<span class="function_ invoke__">print_r</span>($result);
This allows for more precise control over filtering rules and avoids accidentally removing important data.
Using array_filter to remove empty values from an array is highly efficient, eliminating the need to manually iterate over the array or check each element. Depending on your needs, you can use the default behavior to filter false values or define a custom callback for precise filtering. This method is simple, clear, and performs well, making it an essential tool for PHP array handling.
<?php
// End of PHP example, unrelated to article content
echo "PHP example program finished.\n";
?>
Related Tags:
array_filter