PHP

Remove Empty or Null Values from a PHP Array

Learn to clean up PHP arrays by removing elements that are null, empty strings, or evaluate to false, using `array_filter` for concise and efficient code.

<?php

// Example Array with various empty values
$data = [
    'apple',
    null,
    'banana',
    '',
    'orange',
    false,
    0,
    [],
    'grape'
];

// Method 1: Remove all values that evaluate to false (null, empty string, false, 0, empty array)
$filteredData1 = array_filter($data);
print_r($filteredData1);
// Expected output: Array ( [0] => apple [2] => banana [4] => orange [8] => grape )

// Method 2: Remove only null values
$filteredData2 = array_filter($data, function($value) {
    return $value !== null;
});
print_r($filteredData2);
// Expected output: Array ( [0] => apple [2] => banana [3] => [4] => orange [5] => [6] => 0 [7] => Array ( ) [8] => grape )

// Method 3: Remove empty strings and null values (but keep 0 and false)
$filteredData3 = array_filter($data, function($value) {
    return $value !== null && $value !== '';
});
print_r($filteredData3);
// Expected output: Array ( [0] => apple [2] => banana [4] => orange [5] => [6] => 0 [7] => Array ( ) [8] => grape )

?>
How it works: This snippet demonstrates how to remove various 'empty' values from a PHP array using `array_filter`. By default, `array_filter` removes all values that evaluate to `false` (including `null`, empty strings `''`, `0`, and empty arrays `[]`). You can also provide a custom callback function to `array_filter` to define specific conditions for removal, such as only removing `null` values, or filtering out both `null` and empty strings while preserving other 'falsy' values like `0` or `false`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs