How to Remove Empty Values from Multidimensional Array in PHP

Recursively remove empty elements and subarrays from a multi-dimensional array

Try using array_map() to apply the filter to every array in $array:

$array = array_map('array_filter', $array);
$array = array_filter($array);

Demo: http://codepad.org/xfXEeApj

How to remove empty values from multidimensional array in PHP?

Bit late, but may help someone looking for same answer. I used this very simple approach to;

  1. remove all the keys from nested arrays that contain no value, then
  2. remove all the empty nested arrays.

$postArr = array_map('array_filter', $postArr);
$postArr = array_filter( $postArr );

How to remove null values in multi-dimensional array?

Here we are using foreach to iterate over values and using $value for non-empty $value["fcmToken"]

$result=array();
foreach($array as $key => $value)
{
if(!empty($value["fcmToken"]))
{
$result[]=$value;
}
}

print_r($result);

Output:

Array
(
[0] => Array
(
[fcmToken] => dfqVhqdqhpk
)

[1] => Array
(
[fcmToken] => dfgdfhqdqhpk
)

)

remove empty array from multidimensional array

Try to use array_filter() instead since array_shift() just takes care of the first element:

foreach ($cal as &$value) {
$value = array_filter($value);
}

How to remove empty array from multidimensional array in php?

Decided to not go furter with using PHP arrays, just going to call it using js arrays

PHP: remove empty array strings in multidimensional array

To add to Rikesh's answer:

<?php
$aryMain = array(array('hello','bye'), array('',''),array('',''));
$aryMain = array_filter(array_map('array_filter', $aryMain));
print_r($aryMain);

?>

Sticking his code into another array_filter will get rid of the entire arrays themselves.

Array
(
[0] => Array
(
[0] => hello
[1] => bye
)

)

Compared to:

$aryMain = array_map('array_filter', $aryMain);

Array
(
[0] => Array
(
[0] => hello
[1] => bye
)

[1] => Array
(
)

[2] => Array
(
)

)

Can't remove empty keys from multidimensional array

You can use some array functions to remove keys that is empty.

$arr_a = array("AAA","","CCC","");

$arr_b = array("a1","b1","a2","b2","a3","b3","a4","b4");

$arr_c = array_chunk($arr_b,2);

$c = array_combine($arr_a,$arr_c);

$limp= array_filter($c);

$filteredkeys = array_filter(array_keys($limp)); // here i remove the "" key

$filtered = array_intersect_key($limp, array_flip($filteredkeys)); // since $filterdkeys is values i need to flip it and intersect with $limp
var_dump($filtered);

output:

array(2) {
["AAA"]=>
array(2) {
[0]=>
string(2) "a1"
[1]=>
string(2) "b1"
}
["CCC"]=>
array(2) {
[0]=>
string(2) "a3"
[1]=>
string(2) "b3"
}
}

https://3v4l.org/miNeW



Related Topics



Leave a reply



Submit