note 49828 added to function.array-diff

From: Date: Wed, 09 Feb 2005 18:53:05 +0000
Subject: note 49828 added to function.array-diff
Groups: php.notes 
Request: Send a blank email to php-notes+get-84744@lists.php.net to get a copy of this message
if you don't like the php diff (like me) then take look at my diff functions if you have two arrays, lets say: a1 = { blue, red, green } a2 = { blue, yellow, green } array_diff just gives me nothing, although there is a difference. instead of an empty array, i needed an array which should contain "red" and "yellow" in this case. single_diff satisfies my wish. function single_diff(&$a1,&$a2) { $r = array(); // return foreach ($a1 as $pl) // payload { if (! in_array($pl, $a2, true) ) $r[] = $pl; } foreach ($a2 as $pl) // payload { if (! in_array($pl, $a1, true) && ! in_array($pl, $r, true) ) $r[] = $pl; } return $r; } -------------------- this one just keeps the keys of the arrays in mind by comparing the values directly. just in case if there are values, which might occur multiple in one of these arrays. function single_diff_assoc(&$a1,&$a2) { $r = array(); // return foreach ($a1 as $k => $pl) // payload { if (! isset($a2[$k]) || $a2[$k] != $pl) $r[$k] = $pl; } foreach ($a2 as $k => $pl) // payload { if ( (! isset($a1[$k]) || $a1[$k] != $pl ) && ! isset($r[$k]) ) $r[$k] = $pl; } return $r; } recursion support might be useful, but feel free to modify this functions to your own purposes. ---- Manual Page -- http://www.php.net/manual/en/function.array-diff.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+49828 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+49828&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+49828&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+49828&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+49828&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+49828&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+49828&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#84744) next »