Deep clone PHP array

Dani 0 Tallied Votes 287 Views Share

By default, PHP's clone keyword just creates a shallow copy of an object, and doesn't work as desired if the object contains properties that are also objects, because it doesn't create real copies of those objects but rather just pointers to the initial version of them.

This function creates a deep clone of a PHP array or object, in which some of the array elements may be objects.

function deep_clone($array)
{
    if (is_array($array))
    {
        $clone = array();

        foreach ($array AS $key => $value)
        {
            if (is_object($value))
            {
                $clone[$key] = clone $value;
            }
            else
            {
                $clone[$key] = $value;
            }
        }

        return $clone;
    }
    else if (is_object($array))
    {
        $clone = clone $array;

        return $clone;
    }
    else 
    {
        return $array;
    }
}