-1

I have two object to merge.

var obj1 = {a: 1, b: 2, c: 3}
var obj2 = {a: "", b: 4, c: ""}

I want to merge this 2 objects and using JavaScript I can write this code:

function merge_objects(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    for (var attrname in obj1) { 
      if ((obj1[attrname] != "") && (typeof obj1[attrname] != 'undefined')) {
      obj3[attrname] = obj1[attrname]; 
    }
    }
    return obj3;
}

How I can access object properties (not values) using PHP ?

Chris Haas
  • 53,986
  • 12
  • 141
  • 274
Aleks Per
  • 1,549
  • 7
  • 33
  • 68
  • Just so I’m clear, this question has nothing to do with JavaScript in any way, right? You are just showing how you would do this in another language? – Chris Haas Apr 02 '22 at 15:57
  • Are you just wanting to [get the keys](https://www.php.net/manual/en/function.get-object-vars.php) or [test whether a property exists](https://www.php.net/manual/en/function.property-exists.php)? Or can you use [this merging function](https://stackoverflow.com/a/1953077/231316)? – Chris Haas Apr 02 '22 at 15:59
  • yes, nothing with JS, just an example how I build it in JS – Aleks Per Apr 02 '22 at 16:02

1 Answers1

1

Merge only properties:

// setup:
$obj1 = new \stdClass;
$obj1->a = 1; $obj1->b = 2; $obj1->c = 3;

$obj2 = new \stdClass;
$obj2->a = ""; $obj2->b = 4; $obj2->c = "";


function mergePropertiesWithoutValues($obj1, $obj2) 
{
    $properties = array_merge(array_keys(get_object_vars($obj1)), array_keys(get_object_vars($obj2)));

    $obj3 = new \stdClass;
    
    foreach($properties as $property) {
        // Set default value as you wish:
        $obj3->{$property} = null;
    }
    
    return $obj3;
}

var_dump(mergePropertiesWithoutValues($obj1, $obj2));
W S
  • 362
  • 3
  • 4