Search code examples
phpobjectsummerging-data

Sum values from two objects where properties are the same


How can I merge two objects and sum the values of matching properties? I am hoping for a built in function in PHP, otherwise I am seeking an easy way of doing it.

See code under, where I have $objectA and $objectB which I want to become $obj_merged.

$objectA = (object) [];
$objectA->a = 1;
$objectA->b = 1;
$objectA->d = 1;
  
$objectB = (object) [];
$objectB->a = 2;
$objectB->b = 2;
$objectB->d = 2;
  
$obj_merged = (object) [
    'a' => 3,
    'b' => 3,
    'd' => 3
];

Solution

  • What you want to achieve is a sum of the properties. A merge would overwrite the values. There is no built-in PHP function to do this with objects.

    But you can use a simple helper function where you could put in as many objects as you like to sum up the public properties.

    function sumObjects(...$objects): object
    {
        $result = [];
        foreach($objects as $object) {
            foreach (get_object_vars($object) as $key => $value) {
                isset($result[$key]) ? $result[$key] += $value : $result[$key] = $value;
            }
        }
        return (object)$result;
    }
    
    $sumObject = sumObjects($objectA, $objectB);
    
    stdClass Object
    (
        [a] => 3
        [b] => 3
        [d] => 3
    )