note 97425 added to function.array-diff-key
| From: | lukas dot starecek at centrum dot cz | Date: | Mon, 19 Apr 2010 12:47:04 +0000 |
| Subject: | note 97425 added to function.array-diff-key | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-168396@lists.php.net to get a copy of this message | ||
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 :-)
----
Server IP: 147.32.160.17
Probable Submitter: 62.84.131.138
----
Manual Page -- http://www.php.net/manual/en/function.array-diff-key.php
Edit -- https://master.php.net/note/edit/97425
Del: integrated -- https://master.php.net/note/delete/97425/integrated
Del: useless -- https://master.php.net/note/delete/97425/useless
Del: bad code -- https://master.php.net/note/delete/97425/bad+code
Del: spam -- https://master.php.net/note/delete/97425/spam
Del: non-english -- https://master.php.net/note/delete/97425/non-english
Del: in docs -- https://master.php.net/note/delete/97425/in+docs
Del: other reasons-- https://master.php.net/note/delete/97425
Reject -- https://master.php.net/note/reject/97425
Search -- https://master.php.net/manage/user-notes.php