note 60977 added to function.array-diff

From: Date: Sun, 22 Jan 2006 03:26:32 +0000
Subject: note 60977 added to function.array-diff
Groups: php.notes 
Request: Send a blank email to php-notes+get-102224@lists.php.net to get a copy of this message
Even better: <?php # An extention to array_diff: # It returns an array of all values not present in all arrays given. If '$strict' is true, # it returns all values not present or not in the same order in all arrays given. The # arrays to compare must be placed in another array, which is used as argument '$arrays'. # Returns false if '$arrays' is invalid. function array_rdiff ($arrays, $strict = false) { # check if argument is valid. if (!is_array ($arrays)) return false; foreach ($arrays as $array) if (!is_array ($array)) return false; # set working variables $diff = array (); $amount = count ($arrays); $needles = array_shift ($arrays); # compare for ($n = 0; $n < $amount; $n++) { foreach ($needles as $needle) { $found = true; $positions = array (); foreach ($arrays as $haystack) { if (($pos = array_search ($needle, $haystack)) === false) $found = false; if ($strict) $positions[] = $pos; } if (!$found) $diff[] = $needle; elseif ($strict && (count (array_unique ($positions)) > 1)) $diff[] = $needle; } $arrays[] = $needles; $needles = array_shift ($arrays); } return array_unique ($diff); } $array1 = array (1, 2, 3); $array2 = array (1, 2, 3); $array3 = array (1, 3, 2); ?> Doing: <?php print_r (array_rdiff (array ($array1, $array2, $array3))); ?> or <?php print_r (array_rdiff (array ($array1, $array2, $array3), false)); ?> will result in: Array ( ) Doing: <?php print_r (array_rdiff (array ($array1, $array2, $array3), true)); ?> will result in: Array ( [0] => 2 [1] => 3 ) ---- Server IP: 194.109.193.119 Probable Submitter: 82.170.215.175 ---- Manual Page -- http://www.php.net/manual/en/function.array-diff.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+60977 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+60977&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+60977&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+60977&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+60977&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+60977&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+60977&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+60977&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+60977&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#102224) next »