0

Im trying to copy array of objects to a new array. but the reference to the objects in the array are staying the same. my code :

$newArray = $this->ContentArray;
var_dump(newArray[0]->text); //print "text"
var_dump($this->ContentArray[0]->text); //print "text"
$this->ContentArray[0]->text = "edit text"; 
var_dump(newArray[0]->text); //print edit text"

how can I remove the reference to the objects?

1
  • 1
    Typo $this-ContentArray[0]->text = "edit text"; must be $this->ContentArray[0]->text = "edit text"; Commented Feb 17, 2016 at 11:51

2 Answers 2

1

You could explicitely clone each array element:

$newArray = array_map(
    function ($element) { return clone $element; },
    $this->ContentArray
);
array_merge($this->ContentArray,$newArray);

var_dump(newArray[0]->text);
var_dump($this->ContentArray[0]->text);
$this->ContentArray[0]->text = "edit text"; 
var_dump(newArray[0]->text); 

But I prefer the solution from Praveen Kumar.

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

Comments

0

You got a typo: $this-ContentArray[0]->text = "edit text";

Should be $this->ContentArray[0]->text = "edit text";

EDIT And you have tried putting '$' before newArray?

EDIT 2

It seems that Objects in PHP are always passed by reference, even if you. You might want to check out this thread: Passed by reference

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.