note 60976 deleted from function.array-diff by nlopess

From: Date: Sun, 22 Jan 2006 11:28:52 +0000
Subject: note 60976 deleted from function.array-diff by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-102236@lists.php.net to get a copy of this message
Note Submitter: Jappie ---- 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 )

« previous php.notes (#102236) next »