note 60977 deleted from function.array-diff by betz
| From: | betz@php.net | Date: | Tue, 21 Feb 2006 11:28:51 +0000 |
| Subject: | note 60977 deleted from function.array-diff by betz | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-104125@lists.php.net to get a copy of this message | ||
Note Submitter: Jappie
----
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
)