PHP | Clone arrays containing objects

|
| By Webner

In PHP you need deep cloning to clone arrays containing objects.

Suppose we have $cold_items as an array of objects. To clone it appropriately so that while changing the values in one array does not impact the other one, use code like this:

$clonedArray = array();
foreach ($cold_items as $coldItem)
{
$clonedItem = clone $coldItem;//here we are cloning the item
$clonedArray[] = $clonedItem;
}
$clonedArray is now independent array.

Leave a Reply

Your email address will not be published. Required fields are marked *