note 97425 deleted from function.array-diff-key by danbrown

From: Date: Mon, 19 Apr 2010 14:02:29 +0000
Subject: note 97425 deleted from function.array-diff-key by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-168399@lists.php.net to get a copy of this message
Note Submitter: lukas dot starecek at centrum dot cz ---- Hi, recursive version provided by AiFiLTr0 [at host] invyl [dot] ath.cx is bogus. Bug: <?php $a1 = array('arr' => array('aa' => 'bb'), 'xx' => 'yy'); $a2 = array('arr' => array('lsdkfhjsadkf' => 'cc'), 'xx' => 'zz'); array_diff_key_recursive($a1, $a2); ?> This returns bad results. Aditionaly it raises notices. Reason of bug (and illogicality) is, why to call "array_diff_key" in "else"? For each scalar value in $a1 you call array_diff_key on same data ($a1 and $a2). My version: <?php public static function arrayDiffKeyRecursive(array $a1, array $a2) { $r = array(); foreach($a1 as $k => $v) { if (!array_key_exists($k, $a2) || is_array($v) && !empty($v) && !is_array($a2[$k])) { $r[$k] = $v; } elseif (is_array($v) && is_array($a2[$k])) { $diff = self::arrayDiffKeyRecursive($v, $a2[$k]); if (!empty($diff)) { $r[$k] = $diff; } // if } // elseif } // foreach return $r; } // arrayDiffKeyRecursive ?> Question is, how to behave, when in $a1 in some key is array and in $a2 in that same key is scalar value. I prefer to return difference only if array in $a1 is not empty. If anybody want to return this difference, remove "!empty($v)" from if. Any bug reports or improvements are welcome. Hope it will help :-)

« previous php.notes (#168399) next »