PHP

Remove Null, False, and Empty Values from a PHP Array

Clean up PHP arrays by efficiently removing all elements that are considered empty (null, false, empty strings, 0, empty arrays) using a built-in function.

<?php
$mixedArray = [
    'fruit' => 'apple',
    'color' => null,
    'size' => 0,
    'quantity' => '5',
    'available' => false,
    'description' => '',
    'tags' => [],
    'price' => 10.50
];

echo "Original Array:
";
print_r($mixedArray);

// Using array_filter without a callback function removes all empty-like values
$cleanedArray = array_filter($mixedArray);

echo "
Cleaned Array:
";
print_r($cleanedArray);
/* Expected output:
Array
(
    [fruit] => apple
    [quantity] => 5
    [price] => 10.5
)
*/

$anotherArray = [1, '', 0, 'hello', false, null, []];
$anotherCleaned = array_filter($anotherArray);
echo "
Another Cleaned Array:
";
print_r($anotherCleaned);
/* Expected output:
Array
(
    [0] => 1
    [3] => hello
)
*/
?>
How it works: `array_filter()` is a versatile PHP function. When called without a callback function, it automatically removes all elements from an array that evaluate to 'empty'. This includes `null`, `false`, empty strings (`''`), zero (`0`), zero-equivalent floats (`0.0`), and empty arrays (`[]`). This snippet provides a quick and efficient way to clean up arrays by stripping out unwanted or irrelevant empty values.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs