What potential pitfalls should be avoided when working with arrays of objects in PHP?

One potential pitfall when working with arrays of objects in PHP is directly modifying objects within the array without realizing that objects are passed by reference. This can lead to unintended changes in multiple places. To avoid this, make sure to clone objects before modifying them within the array.

// Create an array of objects
$objects = [
    new stdClass(),
    new stdClass(),
    new stdClass()
];

// Clone objects before modifying them
foreach ($objects as $key => $object) {
    $clonedObject = clone $object;
    $clonedObject->property = 'value';
    $objects[$key] = $clonedObject;
}