Voting

: min(three, three)?
(Example: nine)

The Note You're Voting On

xedin dot unknown at gmail dot com
2 months ago
I'm surprized that in the latest PHP 8.4 there still doesn't appear to be an `array_merge_recursive_distinct()`, which I would expect to be included after so many years of people copy-pasting the corresponding note on this page. While I thank the author, as I myself have used it many times, I'd like to suggest a more modern version.

<?php
function array_merge_recursive_distinct(array $array1, array $array2): array
{
foreach (
$array2 as $key => $value) {
if (
is_array($value) && is_array($array1[$key] ?? null)) {
$array1[$key] = array_merge_recursive_distinct($array1[$key], $value);
} else {
$array1[$key] = $value;
}
}

return
$array1;
}
?>

Notable changes:
1. Return type declared.
2. Parameters are not references: that is unnecessary, as the original arrays should not be modified anyway, and due to copy-on-write.
3. Also due to copy-on-write, the `$merged` variable was unnecessary, and has been removed.
4. Check for key existance and whether it is an array combined into one, thanks to the newer `??`.
5. Removed the redundant reference `&$value`.

<< Back to user notes page

To Top