How to Remove Empty Array from MultiDimensional Array in PHP

PHP

Nicesnippets

3341

01-02-2020


Hi Guys,

Today, I will learn you how to remove empty an array from multidimensional array in PHP. You need to remove empty an array in multidimensional array in php then you can use bellow solution.

I will give two solution for remove empty an array in multidimensional array in php. It is easy and simple way to remove empty array. array_filter() function filters the elements of array using a callback function.

Let's see example and you can use anyone as you 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);

?>

It will help you...


Recommended Posts