0

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

1
  • 3
    Don't use references and clone the objects. Commented Aug 29, 2017 at 15:05

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Still facing same issue.
When you call AccumulateRoles($variable) do you use & like AccumulateRoles(&$variable) ?
0

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.
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.