Remove Null Values from a PHP Array: 5 Code Examples (2023)

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to Remove Null Values from an Array in PHP

Use the unset() & is_null() functions to remove null values from a PHP array. You can also use the type check operator “===” as an alternative to the is_null function. You can check for false or use the empty() function if you need to remove any empty value, including nulls.

Removing Null Values from PHP Arrays Code Example

<?php


$array = array('hello', null, 'world', null);


foreach ($array as $key => $value) {
    if ($value === null) {
        unset($array[$key]);
    }
}


print_r(array_Values($array)); // Output: Array ( [0] => hello [1] => world )


?>

Functions to Check for null & empty values in PHP

Function/MethodDescription
isset()Determines if a variable is set and is not null. Returns true if the variable exists and has a value other than null, and false otherwise.
empty()Determines if a variable is considered empty. Returns true if the variable is considered empty, and false otherwise. A variable is considered empty if it does not exist, or if its value equals false, 0, 0.0, "", "0", NULL, [] (an empty array), or stdClass::__set_state([]) (an empty stdClass object).
is_null()Determines if a variable is null. Returns true if the variable is null, and false otherwise.
!The logical NOT operator can also be used to check if a variable is empty, null, or false. For example, !$var will evaluate to true if $var is empty, null, or false, and false otherwise.
===The identity operator can be used to check if a variable is both non-null and of a specific type. For example, $var === null will evaluate to true if $var is null, and $var === 0 will evaluate to false if $var is an empty string or null.

It is important to remove nulls from an array in PHP in many different applications. Removing null values can be helpful for data consistency, processing, and presentation, though it may seem trivial. However, it could be “The Billion Dollar Mistake”.

PHP provides several built-in functions and techniques to remove null values from an array. This article will discuss removing null values from an array in PHP. However, before diving into technicalities, let’s first understand an essential concept of “Falsy” values in PHP.

Article Highlights

  • Falsy values (null, false, 0, ” “, [ ]) coerce to false in a Boolean context.
  • Strict operators are more performant than is_null() in complex scenarios.
  • The simplest way to remove nulls from an array is by using a foreach loop.
  • Another way to remove nulls from an array in PHP is by using the array_filter function.
  • Finally, the array_diff function is also a feasible option for removing nulls from an array.
remove null array php

Table of Contents

What are PHP Falsy Values?

In PHP, falsy values are values that are considered false in a Boolean context. These values represent the absence of a value or an error condition.

In PHP, the following are considered falsy values:

  • null
  • false
  • 0
  • Empty string ("") 
  • Empty array

PHP will coerce (convert) these into false in a Boolean context. For instance, in IF conditions and comparison operators.

Look at the following example to make more sense of it. PHP coerces the falsy values to boolean false before comparison.

<?php


$var1 = null;
$var2 = false;
$var3 = 0;
$var4 = "";
$var5 = array();


var_dump($var1 == false); // Outputs: bool(true)
var_dump($var2 == false); // Outputs: bool(true)
var_dump($var3 == false); // Outputs: bool(true)
var_dump($var4 == false); // Outputs: bool(true)
var_dump($var5 == false); // Outputs: bool(true)


?>

Important Caveats about Falsy Values

When removing null values from an array, it is also essential to consider other falsy values. Otherwise, depending on your use case, these values may be mistakenly included or excluded.

Because of PHP coercing falsy values, you may mistakenly remove 0’s from an array which is not intended in the following example. It was intended to remove nulls only.

<?php


$arr = [1, 0, 0, null, 1, 0, null, 0, 0, 0];


$filteredArray = array_filter($arr, function($value) {
    if($value) return $value; //Removes falsy values.
});


print_r($filteredArray); //[1, 1]


?>

That’s more of a logical error and usually goes unnoticed. Another similar example is using array_filter($array,$callback, $mode = 0) without a callback function. By default, it removes falsy values.

<?php

$arr = [1, 0, 0, null, 1, 0, null, 0, 0, 0];

$filteredArray = array_filter($arr);

print_r($filteredArray); //[1, 1]

?>

Strict Operators | Remove null values from an array in PHP

When checking if a value is null in PHP, it is generally recommended to use strict operators (=== or !==) instead of loose operators (== or !=). This is because loose operators can perform type coercion, resulting in unexpected behaviour. 

Here’s an example that demonstrates the use of strict operators to check if a value is null.

<?php


$value1 = null;
$value2 = "0";


if ($value1 === null) {
    echo "Value 1 is null.\n"; // Output: Value 1 is null.
} else {
    echo "Value 1 is not null.\n";
}


if ($value2 === null) {
    echo "Value 2 is null.\n";
} else {
    echo "Value 2 is not null.\n"; // Output: Value 2 is not null.
}


//Output
//Value 1 is null.
//Value 2 is not null.


?>

is_null(mixed $value) | Remove null values from an array in PHP

PHP has a function that is keen on null values only and not other falsy values.

is_null(mixed $value): bool
  • $value is the value being evaluated.

The function checks if the value is null and returns a boolean accordingly.

=== vs is_null() in PHP | Which one to use?

In terms of performance, === is generally faster than is_null() when checking for null values in PHP. This is because === is a binary operator that compares two values, whereas is_null() is a function call with some additional overhead.

Though it doesn’t make much difference in trivial scenarios, we will use strict operators throughout this article.

Remove Null Values from an Array in PHP using a foreach loop

The most straightforward way to remove null values from an array is to use a foreach loop. It involves iterating through the array and checking each element for null values. If it is null, you can remove an element using the unset($array) function.

Remove Null Values from an Array in PHP using a foreach loop

<?php


$array = array('hello', null, 'world', null);


foreach ($array as $key => $value) {
    if ($value === null) {
        unset($array[$key]);
    }
}


print_r(array_Values($array)); // Output: Array ( [0] => hello [1] => world )


?>

Quite easy! If you wonder about array_values() it is just there for array re-indexing.

Note: If array indexing bothers you, try reading this article.

Remove Null Values from a Multi-dimensional Array in PHP using a foreach loop

The following example will recursively call itself to remove nulls from nested arrays at any level.
We have had sections on recursion and why it is superior most of the time to the iterative approach. Check out the latest article, which talks about these facts.

<?php


function removeNull($array) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            $array[$key] = removeNull($value);
        } else if ($value === null) {
            unset($array[$key]);
        }
    }
    return array_values($array);
}


$array = array('hello', null, array('world', null, 'foo', array(null, "innermost", 0), null), null);


print_r(removeNull($array));


/*
Ouput
Array
(
    [0] => hello
    [1] => Array
        (
            [0] => world
            [1] => foo
            [2] => Array
                (
                    [0] => innermost
                    [1] => 0
                )


        )


)
*/
?>

Let’s understand what this function does.

  • It loops through each key-value pair of the array using a foreach loop
  • If the value of the current pair is an array, the function calls itself recursively, passing the value as the argument, and updates the value of the current pair to the return value of the recursive call.
  • If the value of the current pair is null, the function removes the current key-value pair from the array using the unset() function.
  • The function returns the array with null values removed and re-indexed using array_values().

Remove Null Values from an Array in PHP using array_filter()

Another way to remove null values from an array in PHP is using the built-in function array_filter().

array_filter(array $array, callable $callback = null, int $flag = 0): array

Parameters

  • $array: The array to filter.
  • $callback: The callback function to use. If omitted, removes falsy values from the array.
  • $flag: The optional flag to modify the function’s behaviour.

This function can accept a callback function as an argument. This function applies to each element of the array. 

  • If the callback function returns true for an element, it is included in the resulting array. 
  • If the callback function returns false for an element, it is excluded from the resulting array.

Basic Usage

<?php


$arr = [-3, -2, -1, 0, 1, 2, 3];


$filteredArry = array_filter($arr, function($values) {
        return $values >= 0; //Removes negative numbers.
});


print_r($filteredArry); //Output: [0, 1, 2, 3]


?>

As of PHP 7.4, we can use arrow functions too.

<?php


$arr = [-3, -2, -1, 0, 1, 2, 3];


$filteredArry = array_filter($arr, fn($values) => $values >= 0);


print_r($filteredArry); //Output: [0, 1, 2, 3]


?>

Remove Null Values from an Array in PHP using array_filter()

The following example removes null values from an array in PHP using array_filter().

<?php


$array = array('hello', null, array(), null, "", 3, false, 0, "world");


$filteredArray = array_filter($array, function($value) {
    return $value !== null;
});


print_r($filteredArray); // Output: Array( [0] => hello [2] => Array() [4] => "" [5] => 3 [6] => false [7] => 0 [8] => world)


?>

See how it gets rid of nulls only and spares the rest, including other falsy values.

Remove Null Values from a Multi-dimensional Array in PHP using array_filter()

The following example uses recursion to call array_filter() as many times as it requires to reach the innermost arrays.

<?php


function filter_multi_array_recursive($array)
{
    return array_values(array_filter(array_map(function($value) {
        if (is_array($value)) {
            $value = filter_multi_array_recursive($value); //Recusive call
        }


        return $value;
       
    }, $array), function($value) {
        return $value !== null; //Remove null from the mapped array.
    }));
}




$array = array('hello', null, array('world', null, 'foo', array(null, "innermost", 0), null), null);


print_r(filter_multi_array_recursive($array));


/*
OUTPUT
Array
(
    [0] => hello
    [1] => Array
        (
            [0] => world
            [1] => foo
            [2] => Array
                (
                    [0] => innermost
                    [1] => 0
                )


        )


)
*/
?>

Let’s break this example down for more clarity.

  1. The innermost array_map() recursively call the filter_multi_array_recursive($value) if the $value is an array.
  1. The array_filter() function operates on these arrays and filters the nulls.
  1. Finally, we use array_values() to reindex the innermost arrays.

We know that recursive calls can be confusing. To have a clearer mental model, visualize the recursion in the form of a tree where every part of the tree replicates the same problem.

Remove Null Values from an Array in PHP using array_diff()

In PHP, array_diff() is a built-in function that takes two or more arrays as arguments and returns an array containing all the values from the first array that are not present in any of the subsequent arrays.

array_diff(array $array, array ...$arrays): array

Parameter

  • $array: The array to compare from.
  • $arrays: The arrays to compare against

Basic Usage

<?php

$array1 = [1, 2, 3, 4, 5];
$array2 = [3, 4, 5, 6, 7];


$diff = array_diff($array1, $array2);


print_r($diff); //[1,2]

?>

Remove Null Values from an Array in PHP using array_diff()

The following example removes null values from an array in PHP using array_diff().

<?php


$array = [1, 2, null, 4, null, 6];


$filtered_array = array_diff($array, [null]); //Compare against null to get rid of nulls in $array


print_r($filtered_array); //[1,2]

?>

In this example, $array contains a mixture of non-null values and null values. The array_diff() function compares $array against an array that contains only null. The resulting $filtered_array contains only the non-null values from $array.

Remove Null Values from a Multi-dimensional Array in PHP using array_diff()

<?php


function filter_multi_array_recursive($array) {


    foreach ($array as $key => $value) {
      if (is_array($value)) {
        $array[$key] = filter_multi_array_recursive($value);
      }
    }


    return array_values(array_diff($array, [null]));
}
 


 
$array = array('hello', null, array('world', null, 'foo', array(null, "innermost", 0), null), null);




print_r(filter_multi_array_recursive($array));


/*
OUTPUT
Array
(
    [0] => hello
    [1] => Array
        (
            [0] => world
            [1] => foo
            [2] => Array
                (
                    [0] => innermost
                    [1] => 0
                )


        )


)
*/
?>

Let’s see how it works:

  • It loops through each element of the array using a foreach loop, and for each element.
  • If the element is itself an array, the function recursively calls itself with that element as its argument.
  • It calls array_diff() for every array and sub-array.

Note: The function may issue a warning. It is just because the array_diff() can’t work with a multi-dimensional array by design. You can ignore these warnings.

Frequently Asked Questions

What is the difference between using array_filter() and foreach loop to remove null values from an array in PHP?

The main difference between using array_filter() and a foreach loop to remove null values from an array in PHP is that array_filter() is a built-in function designed explicitly for filtering arrays based on a callback function. In contrast, a foreach loop is a general-purpose looping construct that can manipulate arrays in various ways.

Using array_filter() to remove null values is usually more concise and easier to read, especially with the arrow function in PHP >= 7.4. It also allows for greater flexibility regarding the filtering criteria, as it accepts a callback function that can apply more complex filtering conditions.

On the other hand, a foreach loop can be more efficient in certain situations, particularly when dealing with large arrays or when a more specific type of filtering is required that cannot be easily accomplished with array_filter(). 

What are the benefits of using strict operators (=== or is_null()) to check for null values in PHP?

Strict operators don’t perform type coercion or have an overhead of a function call, making them more performant than is_null() in complex scenarios.

Conclusion

In conclusion, there are several ways to remove null values from an array in PHP, but the most common methods are using a foreach loop, array_filter() and array_diff().

Using a foreach loop is a simple way to remove null values from an array, but it requires writing more code than using built-in functions. On the other hand, array_filter() is more concise with arrow functions and defines a callback to define filter logic. Finally, array_diff() is also a feasible function, except that it issues a warning for the recursive example.

In general, the choice of which method to use will depend on the specific needs of your code. For simple arrays or performance-critical code, array_filter() or array_diff() may be the best choice. A custom function using a foreach loop may be better for more complex situations where recursive filtering is needed.

Hope you have enjoyed this article. Stay tuned for more at FuelingPHP.

PHP Fundamentals Article Series

This article is part of our series on learning the fundamentals of PHP web development. If you are stepping into your PHP journey. Check out the articles in this series to get deeper into PHP.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.