Pankaj
Pankaj

Reputation: 10105

unset element property from array without reference

I have the following function which unset array element's property. During this process, it also unsets from the original array.

Is there any way to update the array element without effecting the original array?

private function AccumulateRoles($Roles) {
    $RoleArray = [];
    foreach($Roles as $key => &$Role) {
        array_push($RoleArray, $Role);
        if(isset($RoleArray[$key]->children)) {
           unset($RoleArray[$key]->children); // This effects $Role also.
        }
    }
}

unset($RoleArray[$key]->children); // This effects $Role also.

I don't want to change $Role

Upvotes: 0

Views: 45

Answers (2)

Pankaj
Pankaj

Reputation: 10105

Below worked for me perfectly by adding clone

private function AccumulateRoles($Roles) {
    $RoleArray = [];
    foreach($Roles as $key => $Role) {
        array_push($RoleArray, clone $Role);
        if(isset($RoleArray[$key]->children)) {
           unset($RoleArray[$key]->children); // This effects $Role also.
        }
    }
}

Upvotes: 0

Edison Biba
Edison Biba

Reputation: 4433

You are using references in your foreach so just remove & and it will work like you want.

private function AccumulateRoles($Roles) {
    $RoleArray = [];
    foreach($Roles as $key => $Role) {
        array_push($RoleArray, $Role);
        if(isset($RoleArray[$key]->children)) {
           unset($RoleArray[$key]->children); // This effects $Role also.
        }
    }
}

Here you have a link to read more about references

Upvotes: 1

Related Questions