Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is array_filter returning a reference?

I would like to understand the difference between these two ( $bookingRows is an array of objects with different properties).

$vehicleRows = [];
foreach($bookingRows as $row) {
 if($row->GroupCode == 'F') {
   $vehicleRows[] = clone $row;
 }
}

and

$vehicleRows = array_values(
 array_filter($bookingRows, function ($row) {
   return $row->GroupCode == 'F';
 })
);

My problem is that if I modify something in the $vehicleRows array, it reflects these changes in the origin, $bookingRows, as well — which is not what I want. How can I avoid such an unwanted reference between the origin and the filtered set of items?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Why does your code use clone? Because otherwise it produces the same result as array_filter().

array_filter() is not the culprit here, the PHP objects are manipulated through a handle. That handle is copied on assignments and this is what array_filter() does. The objects are not duplicated unless one uses clone to explicitly duplicate them.

The PHP documentation page about objects mentions this behaviour:

PHP treats objects in the same way as references or handles, meaning that each variable contains an object reference rather than a copy of the entire object. See Objects and References.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading