note 129782 added to function.array-diff
| From: | xmgr2@protonmail.com | Date: | Fri, 27 Sep 2024 23:36:01 +0000 |
| Subject: | note 129782 added to function.array-diff | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221565@lists.php.net to get a copy of this message | ||
The description is kinda ambiguous at first glance, one might think that the array_diff function
returns the differences across *all* given arrays (which is what I was actually looking for, and
that's why I was surprised that, in the example code, the result did not include
"yellow").
However, i wrote a neat oneliner to compute the differences across all given arrays:
<?php
# Returns an array with values that are unique across all of the given arrays
function array_unique_values(...$arrays) {
return array_keys(array_filter(array_count_values(array_merge(...$arrays)), fn($count) =>
$count === 1));
}
# Example:
$array1 = ['a', 'b', 'c', 'd'];
$array2 = ['a', 'b', 'x', 'y'];
$array3 = ['a', '1', 'y', 'z'];
print_r(array_unique_values($array1, $array2, $array3));
?>
Result:
Array
(
[0] => c
[1] => d
[2] => x
[3] => 1
[4] => z
)
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 2003:c2:3f13:5400:9d59:9998:e5a6:8470)
----
Manual Page -- https://php.net/manual/en/function.array-diff.php
Edit -- https://main.php.net/note/edit/129782
Del: integrated -- https://main.php.net/note/delete/129782/integrated
Del: useless -- https://main.php.net/note/delete/129782/useless
Del: bad code -- https://main.php.net/note/delete/129782/bad+code
Del: spam -- https://main.php.net/note/delete/129782/spam
Del: non-english -- https://main.php.net/note/delete/129782/non-english
Del: in docs -- https://main.php.net/note/delete/129782/in+docs
Del: other reasons-- https://main.php.net/note/delete/129782
Reject -- https://main.php.net/note/reject/129782
Search -- https://main.php.net/manage/user-notes.php