PHP

Filter Out Empty or Null Values from an Array

Learn how to efficiently remove all empty strings, nulls, and falsey values from a PHP array using array_filter, resulting in a clean dataset.

<?php

$data = [
    'name' => 'Alice',
    'email' => '[email protected]',
    'age' => null,
    'city' => '',
    'country' => 'USA',
    'zip' => 0,
    'active' => false,
    'notes' => 'Some notes'
];

// Filter out all values that evaluate to false (null, empty string, 0, false)
$filteredData = array_filter($data);

print_r($filteredData);

/*
Output:
Array
(
    [name] => Alice
    [email] => [email protected]
    [country] => USA
    [notes] => Some notes
)
*/

// To filter specific values, e.g., only nulls:
$dataWithNulls = ['a' => 1, 'b' => null, 'c' => 2, 'd' => null];
$filteredNulls = array_filter($dataWithNulls, function($value) {
    return $value !== null;
});

print_r($filteredNulls);

/*
Output:
Array
(
    [a] => 1
    [c] => 2
)
*/
How it works: The `array_filter()` function is used to filter elements of an array using a callback function. If no callback is supplied, `array_filter()` removes all entries of input that are equivalent to `false` (i.e., `null`, `0`, `""`, `false`, and an empty array). This is extremely useful for cleaning up arrays by removing empty or non-existent data points. The second example demonstrates how to use a custom callback to filter out only `null` values, providing more granular control over the filtering process.

Need help integrating this into your project?

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

Hire DigitalCodeLabs