Why the entry in the array frays object?

There is such code:
$sorted = [];
foreach ($elements as $element_index => $element) {
 foreach ($element->locations as $location_index => $location) {
 $to_push = $element;
 if ($to_push->field_type === 1 or $to_push->field_type === 2 or $to_push->field_type === 4 or $to_push->field_type === 8) {
 $to_push->text_format = $location->text_format;
}
 $to_push->position = $location->position;
 $sorted[$to_push->position->page][] = $to_push;
}

 }

$elements is a model of Eloquent
The problem is that
$sorted[$to_push->position->page][] = $to_push;
And here, for example, we have two iterations for $element->locations where the page number will be the same
Then in the mountains we will have two of the same item equal to the last iteration.

The behavior is very strange, can't understand why it is happening already zadolbalsya to impose a dump from all sides. Inside iterations do different things, and $sorted the same.
June 10th 19 at 14:45
2 answers
June 10th 19 at 14:47
Solution
I don't understand the question, but in the code the problem is most likely here:
$to_push = $element;
$to_push->position = $location->position;

In the end, $sorted = []; we have 2 identical values corresponding to the last iteration, because objects are passed by reference.
But with reference to the variant, how can this be avoided? - freeda89 commented on June 10th 19 at 14:50
to be honest I don't really understand this code (it is not clear that $to_push->text_format = $location->text_format; for example) , you need to rebuild the sort logic, as I think that the clone model is not the best idea - Wava_Berni commented on June 10th 19 at 14:53
must make a split on different locations (this is trebovanie) - freeda89 commented on June 10th 19 at 14:56
June 10th 19 at 14:49
Solution
Problem solved replacing $to_push = $element;
For $to_push = clone $element;

Thanks for the tip

Find more questions by tags LaravelPHP