Merging PHP Objects

Given two objects of same class, merge both objects into a single object.


class MyClass {} 
  
$objectA = new MyClass(); 
$objectA->a = 1; 
$objectA->b = 2; 
$objectA->d = 3; 
  
$objectB = new MyClass(); 
$objectB->d = 4; 
$objectB->e = 5; 
$objectB->f = 6; 
 
// Using array_merge
$obj_merged = (object) array_merge((array) $objectA, (array) $objectB); 
print_r($obj_merged);
stdClass Object
(
    [a] => 1
    [b] => 2
    [d] => 4
    [e] => 5
    [f] => 6
)

// Using array union operator
$obj_union = (object)((array) $objectA +(array) $objectB);        
print_r($obj_union);
stdClass Object
(
    [a] => 1
    [b] => 2
    [d] => 3
    [e] => 5
    [f] => 6
)

PHP array_merge and array union operator

In PHP you can combine arrays using the union operator (+) or the array_merge function.

$ar1 = [
   0  => '1-0',
  'a' => '1-a',
  'b' => '1-b'
];


$ar2 = [
   0  => '2-0',
   1  => '2-1',
  'b' => '2-b',
  'c' => '2-c'
];

print_r($ar1+$ar2);

print_r(array_merge($ar1,$ar2));

The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

Array
(
    [0] => 1-0
    [a] => 1-a
    [b] => 1-b
    [1] => 2-1
    [c] => 2-c
)

array_merge() If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.

Array
(
    [0] => 1-0
    [a] => 1-a
    [b] => 2-b
    [1] => 2-0
    [2] => 2-1
    [c] => 2-c
)