PHP
Filtering Null, Empty, and False Values from a PHP Array
Learn how to quickly clean up a PHP array by removing all null, empty strings, and false boolean values using a simple built-in function.
<?php
$data = ['apple', null, '', 'banana', false, 0, 'orange', true, [], 'grape'];
$cleanedArray = array_filter($data);
// print_r($cleanedArray);
// Expected Output:
// Array
// (
// [0] => apple
// [3] => banana
// [6] => orange
// [7] => 1
// [9] => grape
// )
$strictCleanedArray = array_filter($data, function($value) {
return $value !== null && $value !== ''; // More strict: removes only null and empty strings, keeps false and 0
});
print_r($strictCleanedArray);
How it works: The `array_filter()` function, when called without a callback function, automatically removes all elements that evaluate to `false` (i.e., `null`, `0`, `""`, `false`, `[]`). For more specific filtering, a callback function can be provided to define custom conditions, like strictly removing `null` and empty strings while keeping `false` or `0`.