The Wayback Machine - https://web.archive.org/web/20240624041434/https://www.geeksforgeeks.org/how-to-merge-two-php-objects/
Open In App

How to merge two PHP objects?

Last Updated : 15 Nov, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given two objects of same class and the task is to merge both objects into single object.
Approach 1: Convert object into data array and merge them using array_merge() function and convert this merged array back into object of class stdClass.
Note: While merging the objects using array_merge(), elements of array in argument1 are overwritten by elements of array in argument2. This may nullify the resulting elements in final object if array in argument2 has null values. 
Note: Functions are not copied using this approach. Only use this approach if class only contain variables.
Example: 
 

php




<?php
// PHP program to merge two objects
 
class Geeks {
    // Empty class
}
 
$objectA = new Geeks();
$objectA->a = 1;
$objectA->b = 2;
$objectA->d = 3;
 
$objectB = new Geeks();
$objectB->d = 4;
$objectB->e = 5;
$objectB->f = 6;
 
$obj_merged = (object) array_merge(
        (array) $objectA, (array) $objectB);
         
print_r($obj_merged);
 
?>


Output: 

stdClass Object
(
    [a] => 1
    [b] => 2
    [d] => 4
    [e] => 5
    [f] => 6
)

 

Approach 2: Merge the object using array_merge() method and convert this merged array to object using convertObjectClass function. This function is used to convert object of the initial class into serialized data using serialize() method. Unserialize the serialized data into instance of the final class using unserialize() method. Using this approach obtain an object of user defined class Geeks rather the standard class stdClass.
Example: 
 

php




<?php
// PHP program to merge two objects
 
class Geeks {
    // Empty class
}
 
$objectA = new Geeks();
$objectA->a = 1;
$objectA->b = 2;
$objectA->d = 3;
 
$objectB = new Geeks();
$objectB->d = 4;
$objectB->e = 5;
$objectB->f = 6;
 
// Function to convert class of given object
function convertObjectClass($array, $final_class) {
    return unserialize(sprintf(
        'O:%d:"%s"%s',
        strlen($final_class),
        $final_class,
        strstr(serialize($array), ':')
    ));
}
 
$obj_merged = convertObjectClass(array_merge(
        (array) $objectA, (array) $objectB), 'Geeks');
 
print_r($obj_merged);
 
?>


Output: 

Geeks Object
(
    [a] => 1
    [b] => 2
    [d] => 4
    [e] => 5
    [f] => 6
)

 

Approach 3: Create a new object of the original class and assign all the properties of both objects to this new object by using foreach loop. This is a simple and clean approach of merging two objects.
Example: 
 

php




<?php
// PHP program to merge two objects
 
class Geeks {
    // Empty class
}
 
$objectA = new Geeks();
$objectA->a = 1;
$objectA->b = 2;
$objectA->d = 3;
 
$objectB = new Geeks();
$objectB->e = 4;
$objectB->f = 5;
$objectB->g = 6;
 
// Function to convert class of given object
function convertObjectClass($objectA,
                $objectB, $final_class) {
 
    $new_object = new $final_class();
 
    // Initializing class properties
    foreach($objectA as $property => $value) {
        $new_object->$property = $value;
    }
     
    foreach($objectB as $property => $value) {
        $new_object->$property = $value;
    }
 
    return $new_object;
}
 
$obj_merged = convertObjectClass($objectA,
                        $objectB, 'Geeks');
                         
print_r($obj_merged);
 
?>


Output: 

Geeks Object
(
    [a] => 1
    [b] => 2
    [d] => 3
    [e] => 4
    [f] => 5
    [g] => 6
)

 



Previous Article
Next Article

Similar Reads

How to merge properties of two JavaScript objects dynamically?
Using Spread Operator: Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 values are expected. It allows the privilege to obtain a list of parameters from an array. Javascript objects are key-value paired dictionaries. We can merge different obje
1 min read
How to Merge two Different Arrays of Objects with Unique Values only in JavaScript ?
Merging two arrays of objects with unique values is a common task in JavaScript. This operation involves combining the elements of two arrays while ensuring that each resulting object has a unique identifier. We will explore various approaches to merging two arrays of objects with unique values. These are the following approaches: Table of Content
4 min read
How to Deep Merge Two Objects in TypeScript ?
Merging two objects in TypeScript is a common task, but when dealing with complex nested structures, a deep merge becomes necessary. A deep merge combines the properties of two or more objects, including nested objects, creating a new object with merged values. In this article, we will explore various approaches to deep merging objects in TypeScrip
5 min read
What is the difference between Host objects and Native objects ?
In this article, we will learn about what are Host objects and Native objects, and their differences. JavaScript objects are broadly classified into 2 categories - native javascript objects and host javascript objects. Native objects: Native javascript objects are standard javascript objects which are provided by javascript itself. They are also kn
2 min read
Extract unique objects by attribute from array of objects
Given an array of objects and the task is to return the unique object by the attribute. Examples: Input: [ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 }, { name: 'Geeks', id: 20 }, { name: 'Geeks', id: 10 } ]Output:[ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 } ]Approach: Let's assume that name is an attribute that di
4 min read
How to Separate Array of Objects into Multiple Objects in JavaScript ?
In JavaScript, the task of separating an array of objects into multiple objects involves organizing and restructuring data based on specific criteria or properties. This process is often necessary when dealing with datasets that need to be grouped or segmented for easier analysis or manipulation. There are various methods to achieve this separation
4 min read
Filter Array of Objects with Another Array of Objects in JavaScript
Filtering an array of objects with another array in JavaScript involves comparing and including objects based on specific criteria. Below are the approaches to filter an array of objects with another array of objects in JavaScript: Table of Content Using filter and includes MethodsUsing LoopingUsing reduce MethodUsing filter and includes MethodsIn
3 min read
How to Remove Null Objects from Nested Array of objects in JavaScript ?
Removing null objects from the nested array of objects can be done by iterating over the array, filtering out the null objects at each level, and then applying a recursive approach to remove all the null objects. This makes sure that all the levels of the nested structure are checked and the null objects are removed. There are various approaches to
5 min read
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has various methods to convert an array of objects into
6 min read
How to Remove Multiple Objects from Nested Array of Objects in JavaScript ?
A nested array of objects is an array of arrays that contain multiple objects as their elements. Removing multiple objects from the nested array of objects in JavaSript can be accomplished in different ways as listed below: Table of Content Using filter() with some() methodUsing filter() with includes() methodUsing filter( ) with findIndex() method
6 min read
Article Tags :
three90RightbarBannerImg