Last active
October 28, 2019 08:10
-
-
Save sam-ngu/c92e426f50e8614a4ce93ec2ee0a62a3 to your computer and use it in GitHub Desktop.
PHP: array merge while preserving numeric keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Eg. $array1: | |
array:1 [ | |
3 => array:1 [ | |
"subscription_id" => 27 | |
] | |
] | |
$array2: | |
array:1 [ | |
1 => array:1 [ | |
"subscription_id" => 28 | |
] | |
] | |
array_merge_preserve($array1, $array2); | |
Expected output: | |
3 => array:1 [ | |
"subscription_id" => 27 | |
] | |
1 => array:1 [ | |
"subscription_id" => 28 | |
] | |
*/ | |
function array_merge_preserve(...$arrays) | |
{ | |
$acc = []; | |
foreach ($arrays as $index => $array){ | |
if (empty($acc)) | |
$acc = $array; | |
else | |
$acc += $array; | |
} | |
return $acc; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment