note 60976 added to function.array-diff

From: Date: Sun, 22 Jan 2006 01:38:30 +0000
Subject: note 60976 added to function.array-diff
Groups: php.notes 
Request: Send a blank email to php-notes+get-102223@lists.php.net to get a copy of this message
Reading the comments, I've seen a lot of variations of diff-ing 2 arrays. But what if you need to diff more than 2 arrays? What if you don't know how many arrays you need to diff? This function is an anwer to that: <?php # An extention to array_diff: # It returns an array of all values not present in all arrays given, or null if all match. # The arrays to compare must be placed in an other array, which is used as argument. # Returns false if the given array is invalid. function array_rdiff ($arrays) { # 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 = null; $amount = count ($arrays); $needles = array_shift ($arrays); # compare for ($n = 0; $n < $amount; $n++) { foreach ($needles as $needle) { $found = true; foreach ($arrays as $haystack) if (!in_array ($needle, $haystack)) $found = false; if (!$found) $diff[] = $needle; } $arrays[] = $needles; $needles = array_shift ($arrays); } return array_unique ($diff); } ?> So doing: <?php $array1 = array (21, 22, 23); $array2 = array (21, 12, 23, 24); $array3 = array (11, 22, 23, 24); print_r (array_rdiff (array ($array1, $array2, $array3))); ?> will return: Array ( [0] => 21 [1] => 22 [3] => 12 [4] => 24 [5] => 11 ) ---- 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+60976 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+60976&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+60976&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+60976&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+60976&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+60976&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+60976&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+60976&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+60976&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#102223) next »