How to Remove Empty Array from MultiDimensional Array in PHP

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this blog, I will show you how to remove an empty array from any multidimensional array in PHP application. If we need to remove an empty array from any multidimensional array in php then we can use the bellow solution.

So here I will give you two solution for remove an empty array from multidimensional array in php application. Here it is easy and also it is very simple way to remove an empty array. If we use array_filter() function filters the elements of array by using a callback function.

So Let’s start and see the example and we can use anyone as we need.

Solution

    array_filter(array)

Example 1

<?php
    $students = [
        'student_detail' => 
        [
            'id' => 1,
            'name' => 'abc'
        ],
        [
            'id' => 2,
            'name' => 'def'
        ],
        [],
        [
            'id' => 5,
            'name' => 'jkl'
        ],
        [
            'id' => 6,
            'name' => 'mno'
        ]

    ];

    echo '<pre>';
    print_r($students);

    $students = array_filter($students);
    
    print_r($students);
?>

Example 2

<?php
    $students = [
        'student_detail' => 
        [
            'id' => 1,
            'name' => 'abc'
        ],
        [
            'id' => 2,
            'name' => 'def'
        ],
        [],
        [
            'id' => 5,
            'name' => 'jkl'
        ],
        [
            'id' => 6,
            'name' => 'mno'
        ]

    ];

    echo '<pre>';
    print_r($students);

    foreach($students as $key => $value)          
    if(empty($value)) 
        unset($students[$key]);
    
    print_r($students);
?>

Read Also : Laravel Pagination with Ajax Example

Thank you read.Hope it will help you. Also follow on facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →