note 76940 deleted from ref.array by felipe

From: Date: Sun, 30 Dec 2007 19:30:11 +0000
Subject: note 76940 deleted from ref.array by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-134533@lists.php.net to get a copy of this message
Note Submitter: pedja at uzice dot net ---- Here is the function that cleans array of empty records. It goes recursive through multidimensional array and erases any item that has empty value or is empty array. This actually works on any variable type, not just arrays. <?php function clean_item ($p_value) { if (is_array ($p_value)) { if ( count ($p_value) == 0) { $p_value = null; } else { foreach ($p_value as $m_key => $m_value) { $p_value[$m_key] = clean_item ($m_value); if (empty ($p_value[$m_key])) unset ($p_value[$m_key]); } } } else { if (empty ($p_value)) { $p_value = null; } } return $p_value; } ?> Example: <?php $m_array['aaa'] = 'bbb'; $m_array['ccc'] = ''; $m_array['ddd'] = Array(); $m_array['eee']['fff'] = Array(); $m_array['eee']['ggg'] = ''; $m_array['eee']['hhh'] = 'iii'; $m_array['eee']['j']['a'] = 'gh'; $m_array['eee']['j']['b'] = ''; $m_array['eee']['j']['c'] = 'rty'; $m_array['eee']['j']['d'] = Array(); $m_array['eee']['j']['e'][1] = 'r'; $m_array['eee']['j']['e'][2] = 'y'; $m_array['eee']['j']['e'][1] = ''; $m_array['eee']['j']['e'][4] = Array(); $m_array['eee']['j']['e'][5] = ''; $m_clean = $seo->clean_item ($m_array); print_r ($m_array); print_r ($m_clean); ?> Variable $m_clean contains: Array ( [aaa] => bbb [eee] => Array ( [hhh] => iii [j] => Array ( [a] => gh [c] => rty [e] => Array ( [2] => y ) ) ) ) ?>

« previous php.notes (#134533) next »