note 130103 added to function.array-merge-recursive

From: Date: Fri, 28 Feb 2025 22:36:22 +0000
Subject: note 130103 added to function.array-merge-recursive
Groups: php.notes 
Request: Send a blank email to php-notes+get-221929@lists.php.net to get a copy of this message
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. ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.137 (proxied: 212.65.104.4) ---- Manual Page -- https://php.net/manual/en/function.array-merge-recursive.php Edit -- https://main.php.net/note/edit/130103 Del: integrated -- https://main.php.net/note/delete/130103/integrated Del: useless -- https://main.php.net/note/delete/130103/useless Del: bad code -- https://main.php.net/note/delete/130103/bad+code Del: spam -- https://main.php.net/note/delete/130103/spam Del: non-english -- https://main.php.net/note/delete/130103/non-english Del: in docs -- https://main.php.net/note/delete/130103/in+docs Del: other reasons-- https://main.php.net/note/delete/130103 Reject -- https://main.php.net/note/reject/130103 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221929) next »