In this example, 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
1 2 3 |
array_filter(array) |
Example 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
<?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); ?> |
Example 3: Remove Empty Array Elements and reindex in PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!--?php $array = array("PHP", "Java", 2, null, -5, "Python", 10, false, "", true); $filtered_array = array_filter($array); // filter empty, null, false $filtered_array_reIndex = array_values($filtered_array); // reindex print_r($filtered_array_reIndex ); /* expected output: Array ( [0] =--> PHP [1] => Java [2] => 2 [3] => -5 [4] => Python [5] => 10 [6] => 1 ) */ |
Example 4: How to remove empty associative array entries
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?php $csv_arr = array( 0 => array( 'Enfalac' => 'alpha linolenic acid 300 mg', 'Enfapro' => 'alpha linolenic acid 200 mg' ), 1 => array( 'Enfalac' => 'arachidonic acid 170 mg', 'Enfapro' => '' ), 2 => array( 'Enfalac' => '', 'Enfapro' => '' ), 3 => array( 'Enfalac' => 'calcium 410 mg', 'Enfapro' => 'calcium 550 mg' ) ); $c = function($v){ return array_filter($v) != array(); }; var_dump(array_filter($csv_arr, $c)); ?> |