PHP - remove empty values ​​from an array

Current array:

Array ( [name] => Array ( [name1] => Array ( [0] => some value1 ) [name2] => Array ( [0] => some value2 ) [name3] => Array ( [0] => ) ) 

Required Array:

 Array ( [name] => Array ( [name1] => Array ( [0] => some value1 ) [name2] => Array ( [0] => some value2 ) ) 

Since name3[0] does not contain any value, it must be deleted. From what I read, I have to use array_filter for this, but I can't get it to work.

+4
source share
3 answers

A recursive function, it will remove all empty values ​​and empty arrays from the input array:

 //clean all empty values from array function cleanArray($array) { if (is_array($array)) { foreach ($array as $key => $sub_array) { $result = cleanArray($sub_array); if ($result === false) { unset($array[$key]); } else { $array[$key] = $result; } } } if (empty($array)) { return false; } return $array; } 

I tested it in this example, it works no matter how deep the array is:

 $array = array( 'name' => array( 'name1' => array(0 => 1), 'name2' => array(0 => 3, 1 => array(5 => 0, 1 => 5)), 'name3' => array(0 => '') ) ); 

Hope this helps :)

+3
source

You need to array_filter predicate (function) to array_filter , which determines whether the subelement [0] each array element is empty or not. So:

 $array = array_filter($array, function($item) { return !empty($item[0]); }); 

Remember that empty not very picky: this will delete any element, subelement [0] is an empty string, false , null , 0 or "0" - it will also delete elements that do not have subelement [0] . If you need something more surgically targeted, the test needs to be customized.

+5
source

Can be performed using a recursive function:

 $arr = array('test', array('',0,'test'), array('','')); print_r(clean_array($arr)); function clean_array($array, $isRepeat = false) { foreach ($array as $key => $value) { if ($value === null || $value === '') { unset($array[$key]); } else if (is_array($value)) { if (empty($value)) { unset($array[$key]); } else $array[$key] = clean_array($value); } } if (!$isRepeat) { $array = clean_array($array,true); } return $array; } 
+2
source

Source: https://habr.com/ru/post/1493528/


All Articles