How can foreach() be used to merge data from two objects in PHP, and when is it preferable to array_merge()?

When you need to merge data from two objects in PHP, you can use the foreach() loop to iterate over one object and append its properties to the other object. This method allows you to selectively merge specific properties or perform custom logic during the merging process. On the other hand, if you simply want to merge all properties from both objects without any custom logic, using array_merge() function would be more straightforward and preferable.

// Using foreach() to merge data from two objects
foreach ($object1 as $key => $value) {
    $object2->$key = $value;
}
```

```php
// Using array_merge() to merge two objects
$mergedObject = (object) array_merge((array) $object1, (array) $object2);