How to Remove Null Values From Multidimensional Array In PHP

let's go through an example of how to remove null values from a multidimensional array in PHP. We'll learn how to eliminate null arrays within a multidimensional array in PHP. Here's a step-by-step guide to achieving this.

Table of Contents

  1. Example 1
  2. Output
  3. Example 2
  4. Output

Example 1:

Here, we have an array named $students containing multiple elements, each representing a student. Some of these elements are arrays with student information, and some are null. Then, array_filter is used with a callback function. It iterates through each element in the $students array and keeps only the elements for which the callback function returns true. The callback function checks if the current $student is not null. As a result, this first array_filter removes the null entries from the outer array.

Here, array_map is used to apply a function to each element of the $students array. The function provided to array_map takes a student array and applies another array_filter within it. This inner array_filter removes any null values from each student's array (the inner arrays containing student information).

<?php

    $students = [

        0 => [
            'id' => 1,
            'name' => 'abc'
        ],
        1 => [
            'id' => 2,
            'name' => 'xyz'
        ],
        2 =>null,
        3 => [
            'id' => 4,
            'name' => 'mno'
        ],
        4 => null,
        5 => [
            'id' => 5,
            'name' => 'jkl'
        ],

    ];

    $students = array_filter($students);

    print_r($students);

?>

Output

Example 2:

In example 2, we have an array named $students containing student information. Some of these elements are arrays with student details, and one of the elements is null.

In this loop, you are iterating through each element of the $students array using a foreach loop. The loop assigns the current element's key to $key and the corresponding value to $val.

The if statement checks if the value ($val) is null. If it is, the unset() function is used to remove the element with the current key ($key) from the $students array. This effectively removes the entire element with null value.

<?php

$students = [

    0 => [
        'id' => 1,
        'name' => 'abc'
    ],
    1 => [
        'id' => 2,
        'name' => 'xyz'
    ],
    2 => [
        'id' => 3,
        'name' => 'pqr'
    ],
    3 => [
        'id' => 4,
        'name' => 'mno'
    ],
    4 => null,
    5 => [
        'id' => 5,
        'name' => 'jkl'
    ],

];

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

print_r($students);
?>

Output

That's it for today. I hope it'll be helpful in upcoming project. Thanks for reading. ๐Ÿ™‚