How to Remove Empty Elements from Multidimensional Array in PHP

Before working with a data array, it’s always better to remove empty elements from array. The empty elements can be removed from array using array_filter() function in PHP. But array_filter() function will not remove empty sub-arrays from a multi-dimensional array. If you want to remove empty array elements recursively, an additional function needs to be used with array_filter() function in PHP.

The array_map() and array_filter() function can helps to filter empty elements recursively from multidimensional using PHP. Use the array_map() function with array_filter callback to filter each array in multidimensional array. Using both functions you can easily remove empty elements from multidimensional array in PHP.

  • array_map() function sends the elements of array to the callback function.
  • array_filter() function filters the elements of array using a callback function.

The following code filter and remove all empty array elements from multidimensional array ($array) in PHP.

<?php
$array 
array_map('array_filter'$array);
$array array_filter($array);

2 Comments

  1. Developer Kwame Said...
  2. Pinay Said...

Leave a reply

keyboard_double_arrow_up