Skip to content

Instantly share code, notes, and snippets.

@sam-ngu
Last active October 28, 2019 08:10
Show Gist options
  • Save sam-ngu/c92e426f50e8614a4ce93ec2ee0a62a3 to your computer and use it in GitHub Desktop.
Save sam-ngu/c92e426f50e8614a4ce93ec2ee0a62a3 to your computer and use it in GitHub Desktop.
PHP: array merge while preserving numeric keys
<?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